假设我有一个包含重复值的列表,并且我想删除重复项。
List<int> myList = new List<int>(Enumerable.Range(0, 10000));
// adding a few duplicates here
myList.Add(1);
myList.Add(2);
myList.Add(3);
我找到了 3 种方法来解决这个问题:
List<int> result1 = new HashSet<int>(myList).ToList(); //3700 ticks
List<int> result2 = myList.Distinct().ToList(); //4700 ticks
List<int> result3 = myList.GroupBy(x => x).Select(grp => grp.First()).ToList(); //18800 ticks
//referring to pinturic's comment:
List<int> result4 = new SortedSet<int>(myList).ToList(); //18000 ticks
在关于 SO 的大多数答案中,Distinct方法被显示为“正确的方法”,但 HashSet 总是更快!
我的问题:使用时有什么需要注意的吗?HashSet方法还有其他更有效的方法吗?
这两种方法有很大的区别:
List<int> Result1 = new HashSet<int>(myList).ToList(); //3700 ticks
List<int> Result2 = myList.Distinct().ToList(); //4700 ticks
第一个可以(可能会)改变返回的元素的顺序List<>
: Result1
元素的顺序不会相同myList
的。第二个保持原来的顺序。
可能没有比第一种更快的方法了。
可能没有比第二个“更正确”的了(对于基于排序的“正确”的某个定义)。
(第三个和第二个类似,只是慢一些)
只是出于好奇,Distinct()
is:
// Reference source http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,712
public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source) {
if (source == null) throw Error.ArgumentNull("source");
return DistinctIterator<TSource>(source, null);
}
// Reference source http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,722
static IEnumerable<TSource> DistinctIterator<TSource>(IEnumerable<TSource> source, IEqualityComparer<TSource> comparer) {
Set<TSource> set = new Set<TSource>(comparer);
foreach (TSource element in source)
if (set.Add(element)) yield return element;
}
所以最后Distinct()
只需使用一个内部实现HashSet<>
(称为Set<>
) 检查项目的唯一性。
为了完整起见,我将添加问题的链接C# Distinct() 方法是否保持序列的原始顺序不变? https://stackoverflow.com/q/4734852/613130
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)