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ć?
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ć?
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);
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) –
@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() ' –
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()
}
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);
po co używać var, gdy można zadeklarować bez kosztów ogólnych? – BKSpurgeon
Nie ma "nad głową" w 'var'. –
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());
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])));
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.
+1 dla HashSet. Myślę, że wewnętrznie (z powodu zamówień i innych rzeczy) wykonuje szybsze wyszukiwanie. –
PMSL @ 'bez cukru syntaktycznego. To naprawdę jest inna nazwa składni Metody LINQ. –
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();
Czy mogę też zjeść spaghetti? – Th3B0Y
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
}
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
@nawfal Nie widzę tutaj Linq ... – rene