正如标题所说,我该怎么做?假设我有以下 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);
现在列表temp1
和 temp3
是重复的。我怎样才能删除其中一个?两者都不是 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/