2014-02-27 35 views
2

我需要檢查並顯示包含在列表<>集合中的任何重複項。在列表<>中檢查重複項

//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); 
     } 
    } 
} 

但是,這將返回整個列表。請問我做錯了什麼?

回答

7

您可以使用LINQ代替:

myListCollection.GroupBy(x => x) 
     .Where(x => x.Count() > 1) 
     .Select(x => x.Key) 
     .ToList(); 

首先group所有物品通過他們的價值,然後得到一個包含多個項目組的每個鍵。

你與搜索包含它不會返回精確複製items.For例如,如果你有hellhello它會增加hellolistBox即使它不是一個duplicate.Instead應檢查平等:

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

而且我不認爲你需要的嵌套foreach loop.Anyway,上面的代碼會增加重複的項目,但它仍然是不完全正確。如果你有四個hell將增加四個helllistBox。要解決您可以使用Distinct或者您可以檢查磨損她的項目已經添加,但你不需要。只需使用GroupBy我向您展示了above.Also你可以使用List<T>.ForEach方法把所有項目添加到listBox這樣的:

myListCollection.GroupBy(x => x) 
     .Where(x => x.Count() > 1) 
     .Select(x => x.Key) 
     .ToList() 
     .ForEach(x => listBox1.Items.Add(x)); 
+1

真棒,謝謝! –

0

沒有Linq SOLN。

使用附加的解釋是另一種方式,當空間不是約束:速度:O(n)

using System.IO; 
using System; 
using System.Collections.Generic; 

class Program 
{ 
    static void Main() 
    { 
     // Read in every line in the file. 
     List<string> myListCollection = new List<string>(); 
     myListCollection.Add("hi"); 
     myListCollection.Add("aa"); 
     myListCollection.Add("hi"); 
     myListCollection.Add("hello"); 
     myListCollection.Add("hello"); 
     Dictionary<string,int> dtCollection = new Dictionary<string,int>(); 
     List<string> myDups = new List<string>(); 

     foreach (string y in myListCollection) 
     { 
      if(dtCollection.ContainsKey(y)) 
      { 
          Console.WriteLine(y); 

      }else{ 
       dtCollection.Add(y,1); 
      } 
     } 
    } 
} 
0
List<string> list= new List<string>(); 

for (int i =0 ; i< list.Count(); i++) 
{ 
    for(int k = 0 ; k< list.Count(); k++) 
    { 
    if(list[i] == list[k]) 
    { 
     list.RemoveAt(k); 
     or do something ..../// 
    } 
    } 
} 
相關問題