在字符串数组中查找最常见的字符串

本文关键字:字符串 常见 数组 查找 | 更新日期: 2023-09-27 18:07:50

我有一个问题。有一个字符串

string [5] names = { "John", "Sam", "Harry", "Sam", "John" }

我需要找到数组中最常见的元素。我试着使用:

string MostCommon = names.GroupBy(v => v)
    .OrderByDescending(g => g.Count())
    .First()
    .Key;

不幸的是,它只找到一个元素,例如,MostCommon = John,在这种情况下,我不仅需要John,还需要Sam。我怎么能这么做呢?也许LINQ在这种情况下是不必要的?

在字符串数组中查找最常见的字符串

First显然只选择序列的第一个元素。然而,你需要所有组的数量相等。因此,选择每个组的名称和编号,并在之后顺序。最后选择与第一个组具有相同计数的所有组。

var groups = names.GroupBy(x => x)
    .Select(x => new { x.Key, Count = x.Count() })
    .OrderByDescending(x => x.Count);
int max = groups.First().Count;
var mostCommons = groups.Where(x => x.Count == max);
编辑:你也可以在最后一个语句中使用TakeWhile而不是Where,这将避免对groups列表中的最后一个元素进行不必要的比较,并且当发现第一组元素少于第一个元素时立即停止:
var mostCommons = groups.TakeWhile(x => x.Count == groups.First().Count);

可以这样做-

 var nameGroup = names.GroupBy(x => x);
 var maxCount = nameGroup.Max(g => g.Count());
 var mostCommons = nameGroup.Where(x => x.Count() == maxCount).Select(x => x.Key).ToArray();

根据您找到的最常见名称的计数将您的第一个LINQ与另一个类似的LINQ合并。

string MostCommon = names.GroupBy(v => v)
    .OrderByDescending(g => g.Count())
    .First();
int count = names.Where(x => x == MostCommon).Count();
var mostCommonList = names.GroupBy(v => v)
    .Where(g => g.Count() == count);
//With Dictionary
//This is more useful if you are looking to interview big companies otherwise use the 
 Linq option which is short and handy
public static int MaxOccurrenceOfWord(string[] words)
    {
        var counts = new Dictionary<string, int>();
        int occurrences = 0;
        foreach (var word in words)
        {
            int count;
            counts.TryGetValue(word, out count);
            count++;
             //Automatically replaces the entry if it exists;
            //no need to use 'Contains'
            counts[word] = count;
        }
        string mostCommonWord = null;
        foreach (var pair in counts)
        {
            if (pair.Value > occurrences)
            {
                occurrences = pair.Value;
                mostCommonWord = pair.Key;
            }
        }
        Console.WriteLine("The most common number is {0} and it appears {1} times",
            mostCommonWord, occurrences);
        return occurrences;
    }