C#在字符串数组中查找最常见的字符串 [英] C# Find most common strings in string array

查看:1465
本文介绍了C#在字符串数组中查找最常见的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个问题.有一个字符串

I have this one problem. There is a string

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

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

I need to find the most common elements in the array. I tried using :

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

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

Unfortunately it only finds one element, f.e., MostCommon = John, and in this case I need not only John, but Sam too. How could I do that? Maybe LINQ is not necessary in this case?

推荐答案

这可以按以下步骤完成-

This could be done as follows -

 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();

这篇关于C#在字符串数组中查找最常见的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆