这是一个非常简单的问题,肯定已经被问过并且回答了...但我找不到。
我想使用LINQ从值类型的列表的列表中删除重复项。 我已经尝试了以下方法:
List<List<int>> a = new List<List<int>>() { new List<int>() { 1, 2, 3 }, new List<int>() { 1, 2, 3 }, new List<int>() { 2, 3, 4 } };
// remove duplicates from a
List<List<int>> b = a.Distinct().ToList(); // this doesn't do it
List<List<int>> c = a.Distinct(new ListKeyComparer<int>()).ToList(); // nor does this
internal class ListKeyComparer<TKey> : IEqualityComparer<List<TKey>>
{
public bool Equals(List<TKey> key1, List<TKey> key2)
{
return String.Join("_", key1).Equals(String.Join("_", key2));
}
public int GetHashCode(List<TKey> key)
{
return key.GetHashCode();
}
}
欢迎提出所有解决方案!
List<int> {1,2,2,3,3}
,使用a.Distinct()
会给你返回一个不同的列表。但实际上,你有的是一个列表的列表,每个列表可能包含数字1,但由于列表中的每个列表并不完全相同,它们实际上在开始时就是不同的! - The Muffin Man