4

可能重复:
使用 LINQ 查找数组中出现频率最高的数字

我有一个 int, 的列表,List<int> demoList类似于{1, 2, 1, 1, 1, 3, 2, 1},我想编写一个 LINQ 语句以从该列表中获取出现次数最多的数字,在我的情况下是1.

4

5 回答 5

6
var list = new[] { 1, 2, 1, 1, 1, 3, 2, 1 };
var result = list
    .GroupBy(x => x)
    .Select(x => new { Number = x.Key, Count = x.Count() })
    .OrderByDescending(x => x.Count)
    .FirstOrDefault();
Console.WriteLine("highest number = {0}, count = {1}", result.Number, result.Count);
于 2012-04-26T14:15:33.360 回答
6
 int highestAppearanceNum = demoList.GroupBy(i => i)
            .OrderByDescending(grp => grp.Count())
            .Select(grp => grp.First())
            .First();

编辑:如果您还想知道哪个数字出现的频率:

var appearances = demoList.GroupBy(i => i)
    .OrderByDescending(grp => grp.Count())
    .Select(grp => new { Num = grp.Key, Count = grp.Count() });
if (appearances.Any())
{
    int highestAppearanceNum = appearances.First().Num;     // 1
    int highestAppearanceCount = appearances.First().Count; // 5
}
于 2012-04-26T14:17:07.920 回答
1

使用group by子句。

var groups = 
    from i in demoList
    group i by i into g
    select new { Value = g.Key, Count = g.Count() }

从这里你可以说

var max = groups.Max(g => g.Count);
groups.Where(g => g.Count == max).Select (g => g.Value); // { 1 }
于 2012-04-26T14:14:09.817 回答
1
var query =
    from i in demoList
    group i by i into g
    orderby g.Count() descending
    select new { Value = g.Key, Count = g.Count() };

var result = query.First();
Console.WriteLine(
    "The number with the most occurrences is {0}, which appears {1} times",
    result.Value,
    result.Count);
于 2012-04-26T14:15:37.657 回答
0

我提前致歉:

        List<int> demoList = new List<int>() { 1, 2, 1, 1, 1, 3, 2, 1 };

        Dictionary<int,int> keyOrdered = demoList.GroupBy(i => i)
            .Select(i => new { i.Key, Count = i.Count() })
            .OrderBy(i=>i.Key)
            .ToDictionary(i=>i.Key, i=>i.Count);

        var max = keyOrdered.OrderByDescending(i=>i.Value).FirstOrDefault();

        List<string> histogram = new List<string>();

        for (int i = max.Value; i >-1 ; i--)
        {
            histogram.Add(string.Concat(keyOrdered.Select(t => t.Value>i?"| ":"  ")));
        }

        histogram.Add(string.Concat(keyOrdered.Keys.OrderBy(i => i).Select(i => i.ToString() + " ")));

        histogram.ForEach(i => Console.WriteLine(i));

        Console.WriteLine(Environment.NewLine);
        Console.WriteLine("Max: {0}, Count:{1}", max.Key, max.Value);

当我读到标题时,我想到了这一点,它让我微笑..(也充满了错误!)

于 2012-04-26T15:18:03.993 回答