我有一个班级:
class Item
{
public string eventName{ get; set; }
public string performanceTime { get; set; }
}
我有两个数据列表:
List<string> progName = getProgrammingNames();
List<string> progTimes = getProgrammingTimes()
在两个字符串列表中都有数据,我想将它们合并到
List<Item> itemList = new List<Item>();
我该怎么做?
答案 0 :(得分:9)
使用.Zip
将项目放在一起然后投影Item
类:
var result = progName.Zip(progTimes, (name, time) => new Item {
eventName = name,
performanceTime = time }).ToList();
由于Zip
仅返回具有相同索引的项目,如果一个集合大于其他集合,则会丢失这些项目。在这种情况下,您可以使用完全外部联接的形式:
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 };
答案 1 :(得分:1)
一个简单的For循环是不够的?
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]
});
}