我需要检查并显示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);
}
}
}
但这将返回整个列表。请问我做错了什么?
您可以LINQ
改用:
myListCollection.GroupBy(x => x)
.Where(x => x.Count() > 1)
.Select(x => x.Key)
.ToList();
首先,通过group
所有项的值,然后从包含多个项的组中获取每个键。
您正在搜索的容器中将不会返回完全重复的项目。例如,如果您有容器,即使它不是重复的也将添加到容器中,hell
而应检查是否相等:hello
hello
listBox
foreach (string y in myListCollection)
{
if (myListCollection.FindAll(x => x == y).Count > 1)
{
listbox1.Items.add(y);
}
}
而且我不认为你需要的嵌套foreach
loop.Anyway,上面的代码会增加重复的项目,但它仍然是不完全正确。如果你有四个hell
会增加四个hell
到listBox
。要修复,您可以使用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));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句