在整数列表中查找重复项

约翰

在整数列表中查找重复项的最佳方法是什么(无论thay处于什么位置)?我不需要代码就是解决此问题的最佳方法(在C#中)。

例如:

List<List<int>> TestData = new List<List<int>>
{
     new List<int> { 1, 2, 3 },
     new List<int> { 2, 1, 3 },
     new List<int> { 6, 8, 3, 45,48 },
     new List<int> { 9, 2, 4 },
     new List<int> { 9, 2, 4, 15 },
};

想法是,这将返回

   Count | Set
----------------
   2x    | 1,2,3
   1x    | 6, 8, 3, 45, 48
   1x    | 9,2,4
   1x    | 9, 2, 4, 15

我一直在为这个看似非常简单的问题而烦恼,但由于某种原因,我无法弄清楚。希望有人能够提供帮助,就像我说的那样,代码不是必需的,但我非常感谢。

乔德雷尔

好吧,首先您想将列表转换为集合,

var testSets = testData.Select(s => new HashSet<int>(s));

然后您就可以将集合归为一组。

var groupedSets = testSets.GroupBy(s => s, HashSet<int>.CreateSetComparer());

这是一个完整的示例

using System;
using System.Collections.Generic;
using System.Linq;

public class Test
{
    public static void Main()
    {
        var testData = new List<List<int>>
        {
             new List<int> { 1, 2, 3 },
             new List<int> { 2, 1, 3 },
             new List<int> { 6, 8, 3, 45, 48 },
             new List<int> { 9, 2, 4 },
             new List<int> { 9, 2, 4, 15 }
        };

        var testSets = testData.Select(s => new HashSet<int>(s));

        var groupedSets = testSets.GroupBy(s => s, HashSet<int>.CreateSetComparer());

        foreach(var g in groupedSets)
        {
            var setString = String.Join(", ", g.Key);
            Console.WriteLine($" {g.Count()} | {setString}");
        }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章