使用LINQ C#计算模式

时间:2018-11-29 14:45:19

标签: c#

我是使用Linq的新手,想知道如何打印出Mode值的多个值。目前,我只能从“模式”中获得1个值,但我希望它显示多个值。

string[] list = TextBox1.Text.Split(new string[] { "," }, 
    StringSplitOptions.RemoveEmptyEntries);
int[] numbers = new int[list.Length];
for (int i = 0; i < numbers.Length; i++)
{
    numbers[i] = Convert.ToInt32(list[i].Trim());
}
int mode = numbers.GroupBy(v => v)
                  .OrderByDescending(g => g.Count())
                  .First()
                  .Key;

2 个答案:

答案 0 :(得分:0)

您需要在收藏之前保存好收藏的物品。

string[] list = TextBox1.Text.Split(new string[] { "," }, 
  StringSplitOptions.RemoveEmptyEntries);
IEnumerable<IGrouping<int, int>> modes = list.GroupBy(v => v);
IEnumerable<IGrouping<int, IGrouping<int, int>>> groupedModes = modes.GroupBy(v => v.Count());
var sortedGroupedModes = groupedModes.OrderByDescending(g => g.Key).ToList();

TextBox2.Text = string.Join(" ", sortedGroupedModes[0].Select(x => x.Key)));

答案 1 :(得分:0)

您可以获取所有组,并仅提取计数最高的组(包括关系):

var counts = numbers.GroupBy(v => v)
                    .Select(g => g.Key, Count = g.Count())
                    .OrderByDescending(g => g.Count);

var modes = numbers.Where(g => g.Count == counts.First().Count)
                   .Select(g => g.Key);