我有这样一个类:
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>();
我该怎么做?
最佳答案
使用.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 };
关于c# - 将两个不同的字符串列表合并到一个类列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46443235/