c# - 将两个不同的字符串列表合并到一个类列表中

标签 c# list linq class

我有这样一个类:

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/

相关文章:

java - Vector<Customer> C++、List<Customer> 和 Vector<Customer> Java

linq - 从 "LINQ to SQL"到 "Azure Table Storage"或 "SQL Data Service"

c# - 隐藏 Windows Phone 8.1 的导航按钮

c# - 学习 C#/.NET 是否需要订阅 MSDN?

java 返回包装在 collections.synchronizedlist 中的数组列表的克隆

c# - List.First() 是否返回一个新实例?

c# - Linq 选择某些属性到另一个对象?

c# - 无法下载适用于 Windows Mobile 5.0 应用程序的 EMDK

c# - 使用在外部库中声明的结构反序列化对象

python - 如何从python中的键值对中搜索键