使用LINQ从string []进行多数投票? [英] Majority vote from string[] using LINQ?

查看:84
本文介绍了使用LINQ从string []进行多数投票?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在C#中使用 Linq 查找数组中的大多数元素?更复杂一点的是,如果没有多数,则应该采用第一个元素.

Is there a way to use Linq in C# to find the majority of elements in an array? To make it a bit more complicated, if there is no majority, it should take the first element.

例如,对于数组["A", "B", "B"],该语句的计算结果应为"B". 并且,对于数组["A", "B", "C"],该语句的计算结果应为"A".

So for example with the array ["A", "B", "B"], the statement should evaluate to "B". And, with the array ["A", "B", "C"], the statement should evaluate to "A".

我敢肯定还有100种其他方式可以做到这一点,但对是否有Linq解决方案感到好奇.

I'm sure there are a 100 other ways to do this, but curious if there is a Linq solution.

推荐答案

string majority = yourArray.GroupBy(x => x)
                           .OrderByDescending(g => g.Count())
                           .First()
                           .Key;

查看它是否可以在线运行: ideone

See it working online: ideone

这篇关于使用LINQ从string []进行多数投票?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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