I have a class as such:
class Item
{
public string eventName{ get; set; }
public string performanceTime { get; set; }
}
and I have two lists of data:
List<string> progName = getProgrammingNames();
List<string> progTimes = getProgrammingTimes()
Inside both string lists are data and I would like to merge them to
List<Item> itemList = new List<Item>();
How can I do it?
Use .Zip
to get the items together and then project the Item
class:
var result = progName.Zip(progTimes, (name, time) => new Item {
eventName = name,
performanceTime = time }).ToList();
As Zip
only returns items with same index if one collection is bigger than other it will be missing those items. In that case you can use a form of full outer join:
var result = from i in Enumerable.Range(0, Math.Max(progName.Count, progTimes.Count))
join n in progName.Select((item, index) => new { item, index }) on i equals n.index into names
from n in names.DefaultIfEmpty()
join t in progTimes.Select((item, index) => new { item, index }) on i equals t.index into times
from t in times.DefaultIfEmpty()
select new Item { eventName = n?.item, performanceTime = t?.item };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With