我知道这是基本的,但是如何实现返回最常出现的字段的linq查询?
这是我到目前为止所得到的:
var commonAge = from c in customers.GroupBy(s=>s.age)
.OrderByDescending(sg=>sg.Count())
.Take(1)
select s.Key;
答案 0 :(得分:0)
根据您的评论,您正在寻找具有所述属性的客户数据类型上最常见的Age
。
// Start with the customers collection
var mostCommonAge = customers
// then group by their age,
.GroupBy(c => c.Age,
// and project into a new anonymous type
(key, g) => new {Age = key, Count = g.Count()})
// order by count of each age
.OrderByDescending(g => g.Count)
// and take the first
.First();
这是一个完整的工作示例。使用数据模型类Customer
:
class Customer {
public string Name { get; set; }
public int Age { get;set; }
}
然后您可以按
输出最常见的年龄static void Main(string[] args) {
var customers = new List<Customer> {
new Customer { Age = 23 },
new Customer { Age = 23 },
new Customer { Age = 23 },
new Customer { Age = 24 },
new Customer { Age = 25 }
};
var mostCommonAge = customers
.GroupBy(c => c.Age,
(key, g) => new {Age = key, Count = g.Count()})
.OrderByDescending(g => g.Count)
.First();
Console.WriteLine(mostCommonAge);
}