检查列表<>中的重复项

Mas*_*ick 2 c# list duplicates

我需要检查并显示List <>集合中包含的任何重复项.

//Check for duplicate items
foreach (string y in myListCollection)
{
    if (myListCollection.FindAll(x => x.Contains(y)).Count > 1)
    {
        foreach (string path in myListCollection.FindAll(x => x.Contains(y)))
        {
            listbox1.items.add(path);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但这会返回整个列表.我做错了什么?

Sel*_*enç 7

你可以LINQ改用:

myListCollection.GroupBy(x => x)
         .Where(x => x.Count() > 1)
         .Select(x => x.Key)
         .ToList();
Run Code Online (Sandbox Code Playgroud)

首先,group所有项目的值都会从包含多个项目的组中获取每个项目.

你正在搜索包含它不会返回完全重复的项目.例如,如果你有hell, hello它将添加hellolistBox即使它不是重复.相反你应该检查相等性:

foreach (string y in myListCollection)
{
   if (myListCollection.FindAll(x => x == y).Count > 1)
   {
        listbox1.Items.add(y);
   }
}
Run Code Online (Sandbox Code Playgroud)

而且我不认为你需要的嵌套foreachloop.Anyway,上面的代码会增加重复的项目,但它仍然是不完全正确.如果你有四个hell会增加四个helllistBox.要解决这个问题,你可以使用Distinct 或可以检查项目是否已添加但您不需要.只是GroupBy按照我上面给你的方式使用.也可以使用List<T>.ForEach方法将所有项添加到listBox这样:

myListCollection.GroupBy(x => x)
         .Where(x => x.Count() > 1)
         .Select(x => x.Key)
         .ToList()
         .ForEach(x => listBox1.Items.Add(x));
Run Code Online (Sandbox Code Playgroud)