查找重复的字符串数组

时间:2016-03-22 01:47:41

标签: c# arrays linq list sorting

我有一个很大的字符串数组列表,在这个List<string[]>中,可能存在具有所有相同值(并且可能具有不同索引)的数组。我正在寻找并计算这些重复的字符串数组,并且Dictionary<string[], int>的{​​{1}}是计数(但是如果有比使用字典更好的方法,我会对听证会感兴趣)。有没有人对如何实现这一点有任何建议?任何和所有输入都非常感谢,谢谢!

3 个答案:

答案 0 :(得分:1)

您可以使用linq baseurl: /project-name GroupBy来比较IEqualityComparer

string[]

无序列表的var items = new List<string[]>() { new []{"1", "2", "3" ,"4" }, new []{"4","3", "2", "1"}, new []{"1", "2"} }; var results = items .GroupBy(i => i, new UnorderedEnumerableComparer<string>()) .ToDictionary(g => g.Key, g => g.Count());

IEqualityComparer

.Net Fiddle

答案 1 :(得分:0)

如果您将出现次数用作KeyDictionary,您可能会发现重复键我建议使用Dictionary<string, int>其中key表示字符串,值表示不出现。现在我们可以使用Linq语句。

var results = items.SelectMany(item=>item)
                   .GroupBy(item=>item)
                   .ToDictionary(g=>g.Key, g=>g.Count()); 

其他方法是LookUp,它允许每个映射到一个或多个值的键集合

var lookup = items.SelectMany(item=>item)
                  .GroupBy(item=>item)
                  .ToLookup(c=>c.Count(), c=>c.Key);

工作example

答案 2 :(得分:0)

import java.util.Scanner;
public class Q1 {

public static void main(String[] args) {
    System.out.println("String entry here --> ");
    Scanner input = new Scanner(System.in);
    String entry = input.nextLine();
    String[] words = entry.split("\\s");         
    System.out.println(words.length);
    for(int i=0; i<words.length; i++){
        int count = 0;
        if(words[i] != null){
            for(int j=i+1;j<words.length;j++){
                if(words[j] != null){
                    if(words[i].equals(words[j])){
                        words[j] = null;
                        count++;
                    }
                }
                else{
                    continue;
                }
            }
            if(count != 0){
                System.out.println("Count of duplicate " + words[i] + " = " + count );

            }
        }
        else{
            continue;
        }
    }
    input.close();
}
}