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


当前回答

根据删除重复,我们必须应用下面的逻辑,所以它将以快速的方式删除重复。

public class Program
{

    public static void Main(string[] arges)
    {
        List<string> cities = new List<string>() { "Chennai", "Kolkata", "Mumbai", "Mumbai","Chennai", "Delhi", "Delhi", "Delhi", "Chennai", "Kolkata", "Mumbai", "Chennai" };
        cities = RemoveDuplicate(cities);

        foreach (var city in cities)
        {
            Console.WriteLine(city);
        }
    }

    public static List<string> RemoveDuplicate(List<string> cities)
    {
        if (cities.Count < 2)
        {
            return cities;
        }

        int size = cities.Count;
        for (int i = 0; i < size; i++)
        {
            for (int j = i+1; j < size; j++)
            {
                if (cities[i] == cities[j])
                {
                    cities.RemoveAt(j);
                    size--;
                    j--;
                }
            }
        }
        return cities;
    }
}

其他回答

使用HashSet: list = new HashSet<T>(list).ToList();

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

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

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

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

我认为最简单的方法是:

创建一个新列表并添加唯一的项目。

例子:

        class MyList{
    int id;
    string date;
    string email;
    }
    
    List<MyList> ml = new Mylist();

ml.Add(new MyList(){
id = 1;
date = "2020/09/06";
email = "zarezadeh@gmailcom"
});

ml.Add(new MyList(){
id = 2;
date = "2020/09/01";
email = "zarezadeh@gmailcom"
});

 List<MyList> New_ml = new Mylist();

foreach (var item in ml)
                {
                    if (New_ml.Where(w => w.email == item.email).SingleOrDefault() == null)
                    {
                        New_ml.Add(new MyList()
                        {
                          id = item.id,
     date = item.date,
               email = item.email
                        });
                    }
                }

如何:

var noDupes = list.Distinct().ToList();

在。net 3.5?

你可以使用Union

obj2 = obj1.Union(obj1).ToList();