给出了2个C#列表,说明如何合并它们并从两个列表中仅获取非重复元素

时间:2019-07-12 12:03:47

标签: c# .net

我在C#中有2个列表

List<int> list1 = new List<int> { 78, 92, 100, 37, 81 };
List<int> list2 = new List<int> { 3, 92, 1, 37 };

预期结果应该是

{ 3, 78, 100, 1, 81 }

请注意! 重复9237 不再出现在新列表中。 新列表应该在两个列表中都没有重复的元素。

每个列表不能有重复的值。 理想情况下,我想将其扩展到对象。

我可以手动迭代列表,查找并删除重复项。

我的问题是:使用.NET C#是否有更优雅,更紧凑的方法?

5 个答案:

答案 0 :(得分:3)

您正在寻找SymmetricExceptWith或其仿真,例如

  HashSet<int> result = new HashSet<int>(list1);

  result.SymmetricExceptWith(list2);

让我们看一下这些物品:

  Console.Write(string.Join(", ", result));

结果:

  78, 100, 81, 3, 1

如果您想要List<int>(而不是HashSet<int>)作为结果,请添加ToList()

  List<int> final = result.ToList();      

答案 1 :(得分:1)

var result = list1.Concat(list2).
             GroupBy((g) => g).Where(d => d.Count() == 1).
             Select(d => d.Key).ToList();

答案 2 :(得分:1)

如果您将两个列表相交,然后从它们的并集中减去,您将得到结果:

var result = list1
    .Concat(list2)
    .Except(list1.Intersect(list2))
    .ToList();

答案 3 :(得分:0)

您可以使用Linq的Distinct()方法,给定包含重复项的列表,该方法将返回整数序列中的不同元素。有关Distinct()here的更多信息。

答案 4 :(得分:0)

List<int> list1 = new List<int> { 78, 92, 100, 37, 81 };
List<int> list2 = new List<int> { 3, 92, 1, 37 };

IEnumerable<int> result = list1
    .Concat(list2)              // Concat both lists to one big list. Don't use Union! It drops the duplicated values!
    .GroupBy(g => g)            // group them by values
    .Where(g => g.Count() == 1) // only values which have a count of 1
    .Select(s => s.Key);        // select the values

Console.WriteLine(string.Join(", ", result));