谁有一个快速的方法去重复在c#的泛型列表?
当前回答
正如kronoz在. net 3.5中所说,您可以使用Distinct()。
在。net 2中,你可以模仿它:
public IEnumerable<T> DedupCollection<T> (IEnumerable<T> input)
{
var passedValues = new HashSet<T>();
// Relatively simple dupe check alg used as example
foreach(T item in input)
if(passedValues.Add(item)) // True if item is new
yield return item;
}
这可用于删除任何集合,并将以原始顺序返回值。
通常,过滤一个集合(Distinct()和这个示例都是这样做的)比从其中删除项要快得多。
其他回答
使用HashSet可以很容易地做到这一点。
List<int> listWithDuplicates = new List<int> { 1, 2, 1, 2, 3, 4, 5 };
HashSet<int> hashWithoutDuplicates = new HashSet<int> ( listWithDuplicates );
List<int> listWithoutDuplicates = hashWithoutDuplicates.ToList();
可能更简单的方法是确保没有将重复项添加到列表中。
if(items.IndexOf(new_item) < 0)
items.add(new_item)
正如kronoz在. net 3.5中所说,您可以使用Distinct()。
在。net 2中,你可以模仿它:
public IEnumerable<T> DedupCollection<T> (IEnumerable<T> input)
{
var passedValues = new HashSet<T>();
// Relatively simple dupe check alg used as example
foreach(T item in input)
if(passedValues.Add(item)) // True if item is new
yield return item;
}
这可用于删除任何集合,并将以原始顺序返回值。
通常,过滤一个集合(Distinct()和这个示例都是这样做的)比从其中删除项要快得多。
这将使用distinct(没有重复元素的元素)并再次将其转换为列表:
List<type> myNoneDuplicateValue = listValueWithDuplicate.Distinct().ToList();
简单地用相同类型的List初始化HashSet:
var noDupes = new HashSet<T>(withDupes);
或者,如果你想返回一个List:
var noDupsList = new HashSet<T>(withDupes).ToList();
推荐文章
- 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