LINQ分组
class Data {
    public int A { get; set; }
    public string Name { get; set; }

    public override string ToString()
    {
        return "A:"+A+",Name:"+Name;
    }
}

List<Data> datas = new List<Data>() {
    new Data() { A = 1,Name = "me"},
    new Data(){ A = 10,Name = "hello"},
    new Data(){ A = 5,Name = "world"}
};

var newData = from m in datas group m by m.A into groups select new {key = groups.Key,num= groups.Count() };
foreach (var data in newData) {
    Console.WriteLine(data);
}

group m by m.A 表示以元素的属性A来分组

分组信息into放到groups里

通过groups.Key访问分组的属性,Count()访问该分组的条数


首页 我的博客
粤ICP备17103704号