merging two different string lists to a class list

Viewed 81

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?

2 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 };

A simple For loop is not enough?

        List<string> progName = getProgrammingNames();
        List<string> progTimes = getProgrammingTimes();

        if (progName.Count != progTimes.Count)
            throw new Exception("2 list counts are different");

        List<Item> itemList = new List<Item>();

        for (var l_i = 0; l_i < progName.Count; l_i++)
        {
            itemList.Add(new Item()
            {
                eventName = progName[l_i],
                performanceTime = progTimes[l_i]
            });
        }
Related