从列表中删除重复列表<List<int>>

Remove duplicate List from a List<List<int>>

正如标题所说,我该怎么做?假设我有以下 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,它们也应该被删除

您还可以在添加到列表之前将 Linq 与 SequenceEqual 结合使用:

Console.WriteLine(temp1.SequenceEqual(temp2));//False
Console.WriteLine(temp1.SequenceEqual(temp3));//True

https://msdn.microsoft.com/en-us/library/bb348567(v=vs.110).aspx

您可以使用 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();