谁有一个快速的方法去重复在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();