将两个列表<字符串> 合并以提取常见项目并将其放入列表中

本文关键字:列表 项目 常见 提取 两个 字符串 合并 | 更新日期: 2023-09-27 18:33:20

我有两个列表项,如何编写 linq 查询来比较两者并提取公共项。像列表c,如下所示)

List<string> a = {a, b, c, d}
List<string> b = {c, d, e, f}
List<string> c = {c, d}

将两个列表<字符串> 合并以提取常见项目并将其放入列表中

> 使用 LINQ Intersect 方法。

 var commonItems = a.Intersect(b);

变量 commonItems 将是列表 a 和列表 b 中常见项的集合,这是["c","d"]

您也可以

调用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));

因为它们对两个列表都是通用的,所以我们可以从一个列表中抓取也在另一个列表中的项目。 喜欢这个:

List<string> c = a.Intersect(b)
                  .ToList();

这可以理解为:"从列表 a 中选择项目,以便列表 b 中至少有一个项目具有相同的值。

请注意,这仅适用于具有可用相等方法的值类型和引用类型。

如果要使用 linq where 查询执行此操作:

var c = a.Where(x => b.Contains(x))

Linq 方式:

   List<string> c = (from i in a
                     join j in b
                     on i equals j
                     select i).ToList();