谁有一个快速的方法去重复在c#的泛型列表?
当前回答
David J。的答案是一个很好的方法,不需要额外的对象,排序等。但是,它可以在以下方面进行改进:
for (int innerIndex = items.计数 - 1;内索引 > 外索引 ;内部索引--)
因此,对于整个列表,外部循环会从上到下,但内部循环会从下到“直到到达外部循环的位置”。
外部循环确保整个列表被处理,内部循环找到实际的重复项,这些只会发生在外部循环还没有处理的部分。
或者如果你不想对内循环做自底向上你可以让内循环从outerIndex + 1开始。
其他回答
这里有一个扩展的方法来删除相邻的副本原位。首先调用Sort()并传入相同的ic比较器。这应该比Lasse V. Karlsen的版本更有效,后者重复调用RemoveAt(导致多次块内存移动)。
public static void RemoveAdjacentDuplicates<T>(this List<T> List, IComparer<T> Comparer)
{
int NumUnique = 0;
for (int i = 0; i < List.Count; i++)
if ((i == 0) || (Comparer.Compare(List[NumUnique - 1], List[i]) != 0))
List[NumUnique++] = List[i];
List.RemoveRange(NumUnique, List.Count - NumUnique);
}
所有的答案要么复制列表,要么创建一个新列表,要么使用慢函数,要么就是慢得令人痛苦。
据我所知,这是我所知道的最快和最便宜的方法(同时,还得到了一个非常有经验的实时物理优化程序员的支持)。
// Duplicates will be noticed after a sort O(nLogn)
list.Sort();
// Store the current and last items. Current item declaration is not really needed, and probably optimized by the compiler, but in case it's not...
int lastItem = -1;
int currItem = -1;
int size = list.Count;
// Store the index pointing to the last item we want to keep in the list
int last = size - 1;
// Travel the items from last to first O(n)
for (int i = last; i >= 0; --i)
{
currItem = list[i];
// If this item was the same as the previous one, we don't want it
if (currItem == lastItem)
{
// Overwrite last in current place. It is a swap but we don't need the last
list[i] = list[last];
// Reduce the last index, we don't want that one anymore
last--;
}
// A new item, we store it and continue
else
lastItem = currItem;
}
// We now have an unsorted list with the duplicates at the end.
// Remove the last items just once
list.RemoveRange(last + 1, size - last - 1);
// Sort again O(n logn)
list.Sort();
最终成本为:
nlogn + n + nlogn = n + 2nlogn = O(nlogn)非常漂亮。
关于RemoveRange注意事项: 由于我们不能设置列表的计数并避免使用Remove函数,我不知道这个操作的确切速度,但我猜这是最快的方法。
简单地用相同类型的List初始化HashSet:
var noDupes = new HashSet<T>(withDupes);
或者,如果你想返回一个List:
var noDupsList = new HashSet<T>(withDupes).ToList();
通过Nuget安装MoreLINQ包,你可以很容易地通过属性区分对象列表
IEnumerable<Catalogue> distinctCatalogues = catalogues.DistinctBy(c => c.CatalogueCode);
如果你不关心顺序,你可以把这些项推到HashSet中,如果你想保持顺序,你可以这样做:
var unique = new List<T>();
var hs = new HashSet<T>();
foreach (T t in list)
if (hs.Add(t))
unique.Add(t);
或者用Linq的方式:
var hs = new HashSet<T>();
list.All( x => hs.Add(x) );
编辑:HashSet方法是O(N)时间和O(N)空间,而排序,然后使唯一(由@lassevk和其他人建议)是O(N*lgN)时间和O(1)空间,所以我不太清楚(因为它是第一眼),排序方式是较差的
推荐文章
- HTTP POST返回错误:417“期望失败。”
- 如何在。net中创建和使用资源
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 如何在c#中获得正确的时间戳
- 如何读一个文本文件到一个列表或数组与Python
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 返回大列表中每n项的python方式
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new