c# - 从 List<List<int>> 中删除重复的 List

标签 c# list collections duplicates distinct

正如标题所说,我该怎么做?假设我有以下 List<List<int>> :

var List = new List<List<int>>();
var temp1 = new List<int>();
var temp2 = new List<int>();
var temp3 = new List<int>();

temp1.Add(0);
temp1.Add(1);
temp1.Add(2);

temp2.Add(3);
temp2.Add(4);
temp2.Add(5);

temp3.Add(0);
temp3.Add(1);
temp3.Add(2);

List.Add(temp1);
List.Add(temp2);
List.Add(temp3);

现在列表temp1temp3是重复的。我怎样才能删除其中一个?两者都不是 List.Distinct();不会为我工作。

编辑 此外,如果多个列表的长度为 0,则它们也应该被删除

最佳答案

您可以使用 Distinct() 来完成它,但是使用比较器的重载:

class ListComparer<T> : EqualityComparer<List<T>>
{
    public override bool Equals(List<T> l1, List<T> l2)
    {
        if (l1 == null && l2 == null) return true;
        if (l1 == null || l2 == null) return false;

        return Enumerable.SequenceEqual(l1, l2);
    }


    public override int GetHashCode(List<T> list)
    {
        return list.Count;
    }
}

然后像这样使用它:

var List = new List<List<int>>();
var temp1 = new List<int>();
var temp2 = new List<int>();
var temp3 = new List<int>();

temp1.Add(0);
temp1.Add(1);
temp1.Add(2);

temp2.Add(3);
temp2.Add(4);
temp2.Add(5);

temp3.Add(0);
temp3.Add(1);
temp3.Add(2);

List.Add(temp1);
List.Add(temp2);
List.Add(temp3);


var comparer = new ListComparer<int>();            
var distinct = List.Distinct(comparer).ToList();

您可以先删除空列表:

List = List.Where(l => l.Count > 0).ToList();

关于c# - 从 List<List<int>> 中删除重复的 List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36045773/

相关文章:

c# - 这是什么属性(property)?有必要吗?

c# - C# 中服务器端的文件大小限制

c# - 在没有 t4 代码生成器的情况下创建 Entity Framework (如 vs 2010)

performance - Data.Sequence.Seq 与 [] 相比有多快?

java - 删除元素的最佳集合

c# - 处理只读 List<T> 成员时应该如何使用属性

c# - while 循环没有产生正确的结果

php - laravel 5.2 动态下拉列表

Python:列表分配超出范围

c# - 如何使用 LINQ 按多个项目订购?