I有两个列表项,我如何编写一个linq查询来比较这两个项并提取公共项(如列表c,如下所示)
List<string> a = {a, b, c, d}
List<string> b = {c, d, e, f}
List<string> c = {c, d}
发布于 2016-02-04 19:04:02
使用LINQ Intersect
方法。
var commonItems = a.Intersect(b);
变量commonItems
将是来自list a
和list b
的公共项的集合,即["c","d"]
。
发布于 2016-02-04 19:09:41
您也可以调用List.FindAll
List<string> listA = {a, b, c, d}
List<string> listB = {c, d, e, f}
List<string> listC = listA.FindAll(elem => listB.Contains(elem));
发布于 2016-02-04 19:07:53
因为这两个列表都是通用的,所以我们可以从另一个列表中获取项目。如下所示:
List<string> c = a.Intersect(b)
.ToList();
这可以理解为:“从列表a中选择项,以便列表b中至少有一个项具有相同的值。”
请注意,这仅适用于具有可用相等方法的值类型和引用类型。
https://stackoverflow.com/questions/35209399
复制相似问题