2011-01-02 13 views
82

Mam List<string>, który ma kilka słów powielonych. Muszę znaleźć wszystkie słowa, które są duplikatami.Jak znaleźć wszystkie duplikaty z listy <string>?

Każda sztuczka, żeby je wszystkie zdobyć?

+0

możliwe duplikat [Jak uzyskać duplikaty z listy za pomocą LINQ?] (Http://stackoverflow.com/questions/3811464/how-to-get-duplicate-items-from-a-list-using-linq) – nawfal

+1

@nawfal Nie widzę tutaj Linq ... – rene

Odpowiedz

148

W .NET Framework 3.5 i powyżej można użyć Enumerable.GroupBy która zwraca przeliczalny z enumerables z duplikatów kluczy, a następnie odfiltrować którykolwiek z enumerables które mają hrabiego < = 1, a następnie wybierz swoje klucze wrócić na dół do jednego przeliczalny:

var duplicateKeys = list.GroupBy(x => x) 
         .Where(group => group.Count() > 1) 
         .Select(group => group.Key); 
+3

Daje to wszystkie linie pogrupowane według ich wartości, a nie d uplicuje ... nadal musisz filtrować według 'Count()> 1'. Ponadto, sposób w jaki rozumiem pytanie, każda linia zawiera kilka słów, a OP chce duplikatów słów (ale być może źle zrozumiałem pytanie) –

+31

@Thomas: tak kod nie jest kompletny, ten jest tylko pierwszym krokiem. Następnie może użyć "Gdzie", jeśli chce tylko duplikatów, takich jak 'list.GroupBy (x => x) .Where (group => group.Count()> 1).Wybierz (group => Group.Key) .ToList() ' –

3

Zakładam, że każdy ciąg na liście zawiera kilka słów, daj mi znać, jeśli to jest nieprawidłowe.

List<string> list = File.RealAllLines("foobar.txt").ToList(); 

var words = from line in list 
      from word in line.Split(new[] { ' ', ';', ',', '.', ':', '(', ')' }, StringSplitOptions.RemoveEmptyEntries) 
      select word; 

var duplicateWords = from w in words 
        group w by w.ToLower() into g 
        where g.Count() > 1 
        select new 
        { 
         Word = g.Key, 
         Count = g.Count() 
        } 
17

i bez LINQ:

string[] ss = {"1","1","1"}; 

var myList = new List<string>(); 
var duplicates = new List<string>(); 

foreach (var s in ss) 
{ 
    if (!myList.Contains(s)) 
     myList.Add(s); 
    else 
     duplicates.Add(s); 
} 

// show list without duplicates 
foreach (var s in myList) 
    Console.WriteLine(s); 

// show duplicates list 
foreach (var s in duplicates) 
    Console.WriteLine(s); 
+0

po co używać var, gdy można zadeklarować bez kosztów ogólnych? – BKSpurgeon

+0

Nie ma "nad głową" w 'var'. –

5

Używanie LINQ, oczywiście. Poniższy kod poda ci słownik przedmiotu jako ciąg znaków i liczbę pozycji na twojej liście kwaśnej.

var item2ItemCount = list.GroupBy(item => item).ToDictionary(x=>x.Key,x=>x.Count()); 
2

Na co warto, tu jest mój sposób:

List<string> list = new List<string>(new string[] { "cat", "Dog", "parrot", "dog", "parrot", "goat", "parrot", "horse", "goat" }); 
Dictionary<string, int> wordCount = new Dictionary<string, int>(); 

//count them all: 
list.ForEach(word => 
{ 
    string key = word.ToLower(); 
    if (!wordCount.ContainsKey(key)) 
     wordCount.Add(key, 0); 
    wordCount[key]++; 
}); 

//remove words appearing only once: 
wordCount.Keys.ToList().FindAll(word => wordCount[word] == 1).ForEach(key => wordCount.Remove(key)); 

Console.WriteLine(string.Format("Found {0} duplicates in the list:", wordCount.Count)); 
wordCount.Keys.ToList().ForEach(key => Console.WriteLine(string.Format("{0} appears {1} times", key, wordCount[key]))); 
24

Jeśli używasz LINQ, można użyć następującego zapytania:

var duplicateItems = from x in list 
        group x by x into grouped 
        where grouped.Count() > 1 
        select grouped.Key; 

lub, jeśli go preferują bez cukru syntaktycznego:

var duplicateItems = list.GroupBy(x => x).Where(x => x.Count() > 1).Select(x => x.Key); 

To grupuje wszystkie elementy, które są takie same, a następnie filtruje tylko te grupy, które mają więcej niż jeden element. W końcu wybiera tylko klucz z tych grup, ponieważ nie potrzebujesz tej liczby.

Jeśli wolą nie używać LINQ, można użyć tej metody rozszerzenia:

public void SomeMethod { 
    var duplicateItems = list.GetDuplicates(); 
    … 
} 

public static IEnumerable<T> GetDuplicates<T>(this IEnumerable<T> source) { 
    HashSet<T> itemsSeen = new HashSet<T>(); 
    HashSet<T> itemsYielded = new HashSet<T>(); 

    foreach (T item in source) { 
     if (!itemsSeen.Add(item)) { 
      if (itemsYielded.Add(item)) { 
       yield return item; 
      } 
     } 
    } 
} 

ten śledzi pozycje to widział i przyniósł. Jeśli wcześniej nie widział elementu, dodaje go do listy wyświetlanych elementów, w przeciwnym razie je ignoruje. Jeśli wcześniej nie uzyskał elementu, to go oddaje, w przeciwnym razie go ignoruje.

+0

+1 dla HashSet. Myślę, że wewnętrznie (z powodu zamówień i innych rzeczy) wykonuje szybsze wyszukiwanie. –

+0

PMSL @ 'bez cukru syntaktycznego. To naprawdę jest inna nazwa składni Metody LINQ. –

1
lblrepeated.Text = ""; 
    string value = txtInput.Text; 
    char[] arr = value.ToCharArray(); 
    char[] crr=new char[1];   
    int count1 = 0;   
    for (int i = 0; i < arr.Length; i++) 
    { 
     int count = 0; 
     char letter=arr[i]; 
     for (int j = 0; j < arr.Length; j++) 
     { 
      char letter3 = arr[j]; 
       if (letter == letter3) 
       { 
        count++; 
       }      
     } 
     if (count1 < count) 
     { 
      Array.Resize<char>(ref crr,0); 
      int count2 = 0; 
      for(int l = 0;l < crr.Length;l++) 
      { 
       if (crr[l] == letter) 
        count2++;      
      } 


      if (count2 == 0) 
      { 
       Array.Resize<char>(ref crr, crr.Length + 1); 
       crr[crr.Length-1] = letter; 
      } 

      count1 = count;    
     } 
     else if (count1 == count) 
     { 
      int count2 = 0; 
      for (int l = 0; l < crr.Length; l++) 
      { 
       if (crr[l] == letter) 
        count2++; 
      } 


      if (count2 == 0) 
      { 
       Array.Resize<char>(ref crr, crr.Length + 1); 
       crr[crr.Length - 1] = letter; 
      } 

      count1 = count; 
     } 
    } 

    for (int k = 0; k < crr.Length; k++) 
     lblrepeated.Text = lblrepeated.Text + crr[k] + count1.ToString(); 
+5

Czy mogę też zjeść spaghetti? – Th3B0Y

6

Jeśli szukasz bardziej ogólny sposób:

public static List<U> FindDuplicates<T, U>(this List<T> list, Func<T, U> keySelector) 
    { 
     return list.GroupBy(keySelector) 
      .Where(group => group.Count() > 1) 
      .Select(group => group.Key).ToList(); 
    } 

EDIT: Oto przykład:

public class Person { 
    public string Name {get;set;} 
    public int Age {get;set;} 
} 

List<Person> list = new List<Person>() { new Person() { Name = "John", Age = 22 }, new Person() { Name = "John", Age = 30 }, new Person() { Name = "Jack", Age = 30 } }; 

var duplicateNames = list.FindDuplicates(p => p.Name); 
var duplicateAges = list.FindDuplicates(p => p.Age); 

foreach(var dupName in duplicateNames) { 
    Console.WriteLine(dupName); // Will print out John 
} 

foreach(var dupAge in duplicateAges) { 
    Console.WriteLine(dupAge); // Will print out 30 
} 
Powiązane problemy