谁有一个快速的方法去重复在c#的泛型列表?


当前回答

也许您应该考虑使用HashSet。

从MSDN链接:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        HashSet<int> evenNumbers = new HashSet<int>();
        HashSet<int> oddNumbers = new HashSet<int>();

        for (int i = 0; i < 5; i++)
        {
            // Populate numbers with just even numbers.
            evenNumbers.Add(i * 2);

            // Populate oddNumbers with just odd numbers.
            oddNumbers.Add((i * 2) + 1);
        }

        Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count);
        DisplaySet(evenNumbers);

        Console.Write("oddNumbers contains {0} elements: ", oddNumbers.Count);
        DisplaySet(oddNumbers);

        // Create a new HashSet populated with even numbers.
        HashSet<int> numbers = new HashSet<int>(evenNumbers);
        Console.WriteLine("numbers UnionWith oddNumbers...");
        numbers.UnionWith(oddNumbers);

        Console.Write("numbers contains {0} elements: ", numbers.Count);
        DisplaySet(numbers);
    }

    private static void DisplaySet(HashSet<int> set)
    {
        Console.Write("{");
        foreach (int i in set)
        {
            Console.Write(" {0}", i);
        }
        Console.WriteLine(" }");
    }
}

/* This example produces output similar to the following:
 * evenNumbers contains 5 elements: { 0 2 4 6 8 }
 * oddNumbers contains 5 elements: { 1 3 5 7 9 }
 * numbers UnionWith oddNumbers...
 * numbers contains 10 elements: { 0 2 4 6 8 1 3 5 7 9 }
 */

其他回答

一个简单直观的实现:

public static List<PointF> RemoveDuplicates(List<PointF> listPoints)
{
    List<PointF> result = new List<PointF>();

    for (int i = 0; i < listPoints.Count; i++)
    {
        if (!result.Contains(listPoints[i]))
            result.Add(listPoints[i]);
        }

        return result;
    }

可能更简单的方法是确保没有将重复项添加到列表中。

if(items.IndexOf(new_item) < 0) 
    items.add(new_item)

我有我自己的方式。我是2循环相同的列表比较列表项。然后去掉第二个。

            for(int i1 = 0; i1 < lastValues.Count; i1++)
            {
                for(int i2 = 0; i2 < lastValues.Count; i2++)
                {
                    if(lastValues[i1].UserId == lastValues[i2].UserId)
                    {
                        lastValues.RemoveAt(i2);
                    }
                }
            }

简单地用相同类型的List初始化HashSet:

var noDupes = new HashSet<T>(withDupes);

或者,如果你想返回一个List:

var noDupsList = new HashSet<T>(withDupes).ToList();

在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。