c# - LINQ 加入 2 个列表<T>

标签 c# linq

前言:我不明白这是做什么的:

o => o.ID, i => i.ID, (o, id) => o

所以对我放宽点。 :-)


我有 2 个列表需要连接在一起:

// list1 contains ALL contacts for a customer.
// Each item has a unique ID.
// There are no duplicates.
ContactCollection list1 = myCustomer.GetContacts();

// list2 contains the customer contacts (in list1) relevant to a REPORT
// the items in this list may have properties that differ from those in list1.
/*****/// e.g.:
/*****/        bool SelectedForNotification; 
/*****///  may be different.
ContactCollection list2 = myReport.GetContacts();

我需要创建第三个 ContactCollection,它包含 list1 中的所有联系人,但具有 list2 中项目的属性,如果该项目在列表中[ 2] (list3.Count == list1.Count).


我需要用 list2 中的项目替换 list1 中的所有项目,其中 list1 中的项目具有项目的 ID在 list2 中。结果列表 (list3) 应包含与 list1 相同数量的项目。

我觉得我好像没有任何意义。所以,请在评论中提出问题,我会尽力澄清。

最佳答案

联接并没有那么困难,但是您的问题可能需要进一步的解释。

要加入两个列表,你可以做类似的事情

var joined = from Item1 in list1
             join Item2 in list2
             on Item1.Id equals Item2.Id // join on some property
             select new { Item1, Item2 };

这将给出 IEnumerable<'a> ,其中 'a 是一个匿名类型,其中包含 list1 中的一项及其来自 list2 的相关项。然后,您可以根据需要选择要使用的对象的属性。

要将结果放入具体列表,只需调用 .ToList() 即可。你可以这样做

var list3 = joined.ToList();
// or
var list3 = (from Item1 in list1
             join Item2 in list2
             on Item1.Id equals Item2.Id // join on some property
             select new { Item1, Item2 }).ToList();

要进行左连接以选择 list1 中的所有元素,即使 list2 中没有匹配项,您可以这样做

var list3 = (from Item1 in list1
             join Item2 in list2
             on Item1.Id equals Item2.Id // join on some property
             into grouping
             from Item2 in grouping.DefaultIfEmpty()
             select new { Item1, Item2 }).ToList();

这将为您提供一个列表,其中 Item1 等于第一个列表中的项目,而 Item2 等于第二个列表中的匹配项目默认值,对于引用类型将为 null。

关于c# - LINQ 加入 2 个列表<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2723985/

相关文章:

c# - 将十进制字符串解析为字节

c# - Process.Start 不创建子进程(端口句柄继承)?

c# - 查找与其他列表元素有 3 个属性相似的列表元素,然后将第二个元素的值添加到第一个元素

linq - 嵌套的Linq查询

linq - 如何使用 LINQ 将 xml 文件转换为对象

c# - 如何使用C#获取Win7的SSID和RSSI

c# - 如何在 ASP.NET 中获取 session 状态对象的集合?

c# - Linq2Sql -> 根据本地值集合搜索数据库 - "Queries with local collections are not supported"

c# - Linq 查询 - 列上不同的数据类型

c# - 无法从文本框传递变量