Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merging two different string lists to a class list

Tags:

c#

list

class

linq

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?

like image 525
shikiko Avatar asked Dec 24 '22 13:12

shikiko


1 Answers

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 };
like image 98
Gilad Green Avatar answered Jan 15 '23 02:01

Gilad Green