我有一个int List<int> demoList
的列表,类似于{1, 2, 1, 1, 1, 3, 2, 1}
,我想编写一个LINQ语句来获取该列表中出现次数最多的数字,这在我的案例是1
。
答案 0 :(得分: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);
答案 1 :(得分: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
}
答案 2 :(得分: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 }
答案 3 :(得分: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);
答案 4 :(得分: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);
当我读到标题时,我想到了这一点,它让我微笑..(也充满了虫子!)