gpt4 book ai didi

c# - 在整数列表的列表中查找重复项

转载 作者:行者123 更新时间:2023-11-30 14:24:21 24 4
gpt4 key购买 nike

在整数列表的列表中查找重复项的最佳方法是什么(无论它们位于什么位置)?我不需要代码只是解决这个问题的最佳方法(在 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());

这是一个fully working example ,

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

关于c# - 在整数列表的列表中查找重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41442119/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com