在 C# 中组合视图状态或在 C# 中组合泛型列表
本文关键字:组合 列表 泛型 视图状态 | 更新日期: 2023-09-27 18:36:56
我有以下两个视图状态,一个存储所有开始日期,另一个存储特定事件的所有结束日期:
private List<DateTime> SelectedStartDates
{
get
{
if (ViewState["SelectedStartDates"] != null)
return (List<DateTime>)ViewState["SelectedStartDates"];
return new List<DateTime>();
}
set
{
ViewState["SelectedStartDates"] = value;
}
}
private List<DateTime> SelectedEndDates
{
get
{
if (ViewState["SelectedEndDates"] != null)
return (List<DateTime>)ViewState["SelectedEndDates"];
return new List<DateTime>();
}
set
{
ViewState["SelectedEndDates"] = value;
}
}
问题:
有没有办法让我可以通过以下方式将值的组合列表存储在这两个视图状态中:
List[0] = first value of Start date
List[1] = first value of End date
List[2] = second value of Start date
List[3] = second value of End date
.
.
.
依此类推,直到视图状态中两个列表的最后一个值。
我能想到的另一种方法是以上述方式再次组合视图状态返回的泛型列表。
另外,我想将重复值保留在组合列表中
有
你可以这样做:
List<DateTime> combine = new List<DateTime>();
for (int i = 0; i < SelectedStartDates.Count; i++)
{
combine.Add(SelectedStartDates[i]);
combine.Add(SelectedEndDates[i]);
}
如果两个输入列表是List<string>
类型,并且这些列表中的每个项目都是有效的DateTime
(例如,它的项目由(DateTime).ToString()
函数插入),则可以使用:
List<string> SelectedStartDates = new System.Collections.Generic.List<string>();
List<string> SelectedEndDates = new System.Collections.Generic.List<string>();
List<DateTime> combine = new List<DateTime>();
for (int i = 0; i < SelectedStartDates.Count; i++)
{
combine.Add(DateTime.Parse(SelectedStartDates[i]));
combine.Add(DateTime.Parse(SelectedEndDates[i]));
}
您不确定字符串DateTime
格式是否有效,您可以使用 DateTime.TryParse
.
您可以阅读:
- 日期时间.解析;
- DateTime.ParseExact;
- DateTime.TryParse;
- DateTime.TryParseExact (我的工作答案)
如果你想像你说的那样,直到两个列表的最小计数,那么你可以使用 Zip() 方法。 即:
SelectedStartDates.Zip( SelectedEndDates, (s, e) => new
{Start = s, End = e});