Reputation: 1055
I have the following two ViewStates 1 storing all the start dates and the other storing all the End dates of a particular event:
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;
}
}
Question:
Is there a way in which I can have a combined List of values stored in these two ViewStates in the following manner:
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
.
.
.
and so on till the last value of both the Lists in the ViewState.
The other way I can think of is to combine the Generic List returned by the ViewState again in a manner as mentioned above.
Also, I would like to keep the duplicate values in the combined list
Is there a work-around for this?
Upvotes: 1
Views: 78
Reputation: 8025
You can do like this:
List<DateTime> combine = new List<DateTime>();
for (int i = 0; i < SelectedStartDates.Count; i++)
{
combine.Add(SelectedStartDates[i]);
combine.Add(SelectedEndDates[i]);
}
If two input lists is List<string>
type, and each items in these lists are valid DateTime
(for example, it item is inserted by (DateTime).ToString()
function), you can use:
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]));
}
You you're not sure about if a string is valid DateTime
format or not, you can use DateTime.TryParse
.
You can read about:
Upvotes: 2
Reputation: 23797
If you want to have it like you said, up until the minimum count of both lists, then you can use the Zip() method. ie:
SelectedStartDates.Zip( SelectedEndDates, (s, e) => new
{Start = s, End = e});
Upvotes: 1