C# 如何从列表中查找所有重复项<;字符串>;?

C# 如何从列表中查找所有重复项<;字符串>;?,c#,list,duplicates,C#,List,Duplicates,我有一个列表,其中有一些重复的单词。我需要找到所有重复的单词 有什么窍门可以把它们全部取出来吗?我假设列表中的每个字符串都包含几个单词,如果不正确,请告诉我 List<string> list = File.RealAllLines("foobar.txt").ToList(); var words = from line in list from word in line.Split(new[] { ' ', ';', ',', '.', ':', '('

我有一个
列表
,其中有一些重复的单词。我需要找到所有重复的单词


有什么窍门可以把它们全部取出来吗?

我假设列表中的每个字符串都包含几个单词,如果不正确,请告诉我

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()
                     }
List List=File.reallalllines(“foobar.txt”).ToList();
var words=来自列表中的行
从.Split行中的单词(新[]{'、';'、'、'、'、'、'、'、':'、'('、')},StringSplitOptions.RemoveEmptyEntries)
选择单词;
var duplicateWords=来自w的文字
由w.ToLower()将w分组为g
其中g.Count()>1
选择新的
{
Word=g.Key,
Count=g.Count()
}

在.NET framework 3.5及更高版本中,您可以使用
Enumerable.GroupBy
,它返回重复键的可枚举项,然后过滤掉任何计数为且没有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);
string[]ss={“1”、“1”、“1”};
var myList=新列表();
var duplicates=新列表();
foreach(ss中的var s)
{
如果(!myList.Contains))
myList.Add(s);
其他的
副本。添加;
}
//显示没有重复项的列表
foreach(myList中的var s)
控制台。写入线(s);
//显示重复列表
foreach(变量s重复)
控制台。写入线(s);
当然,使用LINQ。 下面的代码将为您提供项作为字符串的字典,以及sourc列表中每个项的计数

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

无论如何,我的方法是:

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])));
List List=新列表(新字符串[]{“猫”、“狗”、“鹦鹉”、“狗”、“鹦鹉”、“山羊”、“鹦鹉”、“马”、“山羊”});
字典字数=新字典();
//数一数:
list.ForEach(word=>
{
字符串关键字=word.ToLower();
如果(!wordCount.ContainsKey(键))
添加(键,0);
字数[键]+;
});
//删除仅出现一次的单词:
FindAll(word=>wordCount[word]==1).ForEach(key=>wordCount.Remove(key));
WriteLine(string.Format(“在列表中找到{0}个重复项:”,wordCount.Count));
ForEach(key=>Console.WriteLine(string.Format({0}出现{1}次),key,wordCount[key]);

如果使用LINQ,可以使用以下查询:

var duplicateItems = from x in list
                     group x by x into grouped
                     where grouped.Count() > 1
                     select grouped.Key;
或者,如果您喜欢不加语法糖:

var duplicateItems = list.GroupBy(x => x).Where(x => x.Count() > 1).Select(x => x.Key);
这将对所有相同的元素进行分组,然后仅筛选到具有多个元素的组。最后,它只从这些组中选择密钥,因为您不需要计数

如果不希望使用LINQ,可以使用以下扩展方法:

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;
            }
        }
    }
}
public方法{
var duplicateItems=list.GetDuplicates();
…
}
公共静态IEnumerable GetDuplicates(此IEnumerable源){
HashSet itemssen=新的HashSet();
HashSet itemsyieled=新HashSet();
foreach(源中的T项){
如果(!itemsSeen.Add(item)){
如有(项目屏蔽添加(项目)){
收益回报项目;
}
}
}
}
这将跟踪它所看到和产生的项目。如果以前未看到某个项目,则会将其添加到已看到项目的列表中,否则会忽略该项目。如果之前未生成项目,则生成该项目,否则将忽略该项目。

lblrepeated.Text=“”;
    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();
字符串值=txtInput.Text; char[]arr=value.ToCharArray(); 字符[]crr=新字符[1]; int count1=0; 对于(int i=0;i
如果您正在寻找更通用的方法:

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();
    }
找到重复的公共静态列表(此列表,Func键选择器)
{
返回列表.GroupBy(keySelector)
.Where(group=>group.Count()>1)
.Select(group=>group.Key).ToList();
}
编辑:以下是一个示例:

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
}
公共类人物{
公共字符串名称{get;set;}
公共整数{get;set;}
}
List List=newlist(){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(duplicateNames中的var dupName){
Console.WriteLine(dupName);//将打印出John
}
foreach(var dupAge,重复中){
Console.WriteLine(dupAge);//将打印30
}

我使用这样的方法来检查字符串中的重复条目:

public static IEnumerable<string> CheckForDuplicated(IEnumerable<string> listString)
{
    List<string> duplicateKeys = new List<string>();
    List<string> notDuplicateKeys = new List<string>();
    foreach (var text in listString)
    {
        if (notDuplicateKeys.Contains(text))
        {
            duplicateKeys.Add(text);
        }
        else
        {
            notDuplicateKeys.Add(text);
        }
    }
    return duplicateKeys;
}
公共静态IEnumerable CheckForDuplicated(IEnumerable listString)
{
List duplicateKeys=新列表();
List notDuplicateKeys=新列表();
foreach(listString中的var文本)
{
如果(n)
public static IEnumerable<string> CheckForDuplicated(IEnumerable<string> listString)
{
    List<string> duplicateKeys = new List<string>();
    List<string> notDuplicateKeys = new List<string>();
    foreach (var text in listString)
    {
        if (notDuplicateKeys.Contains(text))
        {
            duplicateKeys.Add(text);
        }
        else
        {
            notDuplicateKeys.Add(text);
        }
    }
    return duplicateKeys;
}