【问题标题】:Given 2 C# Lists how to merge them and get only the non duplicated elements from both lists给定 2 个 C# 列表,如何合并它们并仅从两个列表中获取非重复元素
【发布时间】:2019-11-22 04:50:41
【问题描述】:

我在 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# 中是否有更优雅、更紧凑的方法?

【问题讨论】:

标签: c# .net


【解决方案1】:
var result = list1.Concat(list2).
             GroupBy((g) => g).Where(d => d.Count() == 1).
             Select(d => d.Key).ToList();

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:
        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));
        

        【讨论】:

          【解决方案5】:

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

            HashSet<int> result = new HashSet<int>(list1);
          
            result.SymmetricExceptWith(list2);
          

          我们来看看物品:

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

          结果:

            78, 100, 81, 3, 1
          

          如果您想要List&lt;int&gt;(而不是HashSet&lt;int&gt;)作为结果,请添加ToList()

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

          【讨论】:

            猜你喜欢
            • 2015-09-02
            • 1970-01-01
            • 1970-01-01
            • 2022-07-24
            • 1970-01-01
            • 1970-01-01
            • 2021-06-13
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多