谁有一个快速的方法去重复在c#的泛型列表?
当前回答
在Java中(我认为c#或多或少是相同的):
list = new ArrayList<T>(new HashSet<T>(list))
如果你真的想改变原来的列表:
List<T> noDupes = new ArrayList<T>(new HashSet<T>(list));
list.clear();
list.addAll(noDupes);
为了保持顺序,只需将HashSet替换为LinkedHashSet。
其他回答
这将使用distinct(没有重复元素的元素)并再次将其转换为列表:
List<type> myNoneDuplicateValue = listValueWithDuplicate.Distinct().ToList();
可能更简单的方法是确保没有将重复项添加到列表中。
if(items.IndexOf(new_item) < 0)
items.add(new_item)
简单地用相同类型的List初始化HashSet:
var noDupes = new HashSet<T>(withDupes);
或者,如果你想返回一个List:
var noDupsList = new HashSet<T>(withDupes).ToList();
所有的答案要么复制列表,要么创建一个新列表,要么使用慢函数,要么就是慢得令人痛苦。
据我所知,这是我所知道的最快和最便宜的方法(同时,还得到了一个非常有经验的实时物理优化程序员的支持)。
// 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函数,我不知道这个操作的确切速度,但我猜这是最快的方法。
在Java中(我认为c#或多或少是相同的):
list = new ArrayList<T>(new HashSet<T>(list))
如果你真的想改变原来的列表:
List<T> noDupes = new ArrayList<T>(new HashSet<T>(list));
list.clear();
list.addAll(noDupes);
为了保持顺序,只需将HashSet替换为LinkedHashSet。
推荐文章
- 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