可能重复:
使用 LINQ 查找数组中出现频率最高的数字
我有一个 int, 的列表,List<int> demoList
类似于{1, 2, 1, 1, 1, 3, 2, 1}
,我想编写一个 LINQ 语句以从该列表中获取出现次数最多的数字,在我的情况下是1
.
可能重复:
使用 LINQ 查找数组中出现频率最高的数字
我有一个 int, 的列表,List<int> demoList
类似于{1, 2, 1, 1, 1, 3, 2, 1}
,我想编写一个 LINQ 语句以从该列表中获取出现次数最多的数字,在我的情况下是1
.
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);
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
}
使用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 }
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);
我提前致歉:
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);
当我读到标题时,我想到了这一点,它让我微笑..(也充满了错误!)