.net 给定两个C#列表,如何合并它们并从两个列表中只获取非重复的元素

sc4hvdpw  于 2023-03-04  发布在  .NET
关注(0)|答案(5)|浏览(119)

我在C#中有两个列表

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#?

cngwdvgl

cngwdvgl1#

您正在查找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();
8yparm6h

8yparm6h2#

如果求两个列表的交集,然后从它们的并集中减去它,你会得到结果:

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

wgxvkvu93#

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

bqf10yzr4#

你可以使用Linq中的Distinct()方法,如果给定一个包含重复项的列表,它会返回整数序列中的不同元素。

kgqe7b3p

kgqe7b3p5#

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

相关问题