C# 类的最常用属性的Linq查询

C# 类的最常用属性的Linq查询,c#,database,linq,C#,Database,Linq,我知道这是非常基本的,但是如何实现返回最常出现字段的linq查询呢 到目前为止,我得到的是: var commonAge = from c in customers.GroupBy(s=>s.age) .OrderByDescending(sg=>sg.Count()) .Take(1) select s.Key;

我知道这是非常基本的,但是如何实现返回最常出现字段的linq查询呢

到目前为止,我得到的是:

var commonAge = from c in customers.GroupBy(s=>s.age)
                                   .OrderByDescending(sg=>sg.Count())
                                   .Take(1)
                select s.Key; 

根据您的评论,您正在查找具有上述属性的客户数据类型上最常见的
年龄

// 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();

下面是一个完整的工作示例。使用数据模型类
客户

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);

}
static void Main(字符串[]args){
var客户=新列表{
新客户{Age=23},
新客户{Age=23},
新客户{Age=23},
新客户{Age=24},
新客户{Age=25}
};
var mostCommonAge=客户
.GroupBy(c=>c.年龄,
(key,g)=>new{Age=key,Count=g.Count()})
.OrderByDescending(g=>g.Count)
.First();
控制台写入线(大多数常见);
}

欢迎使用堆栈溢出!你能告诉我们更多的细节吗:到目前为止你的代码,你尝试了什么,遇到了什么问题?谢谢你的回复。这就是我目前得到的。var commonAge=来自customers.GroupBy(s=>s.age)中的c.OrderByDescending(sg=>sg.Count()).Take(1)选择s.Key;您至少应该通过示例输出等显示您的数据是什么样子、您想要什么。