linq aggregate

╄→гoц情女王★ 提交于 2019-12-12 08:12:46

问题


class Category
{        
    public string Name { get; set; }
    public int Count { get; set;}
}


Name Count
AA   2
BB   3
AA   4

I have an IEnumerable<Category>

and would like to get a list of Categories with unique names and the sum of multiple entries

Output

Name Count
AA   6
BB   3

Update

class Category 
{ 
public string Name { get; set; } 
public int CountA { get; set;} 
public int CountB { get; set;} 
public string Phone { get; set;} 
}

How would I sum two columns. and the phone column can be the last row or any row


回答1:


var foo = new List<Category>() { 
                new Category() { Name = "AA", Count = 2},
                new Category() { Name = "BB", Count = 3},
                new Category() { Name = "AA", Count = 4}
            };

            var bar = foo.GroupBy(c => c.Name).Select(g => new Category(){ Name = g.Key, Count = g.Sum(c => c.Count) });



回答2:


Your updated question isn't entirely clear in terms of the phone number, but I suspect you want something like:

    var query = from category in list
                group category by category.Name into grouped
                select new { Name = grouped.Key,
                             SumA = grouped.Sum(x => x.CountA),
                             SumB = grouped.Sum(x => x.CountB),
                             Phone = grouped.Last().Phone };

Changing grouped.Last() to grouped.First() would be more efficient, by the way.

Evaluating multiple aggregates in this way isn't terribly efficient in general. The Push LINQ project developed by myself and Marc Gravell makes it a lot more efficient at the cost of not being quite as easy to use. You might want to look into it if you need to deal with a lot of data.



来源:https://stackoverflow.com/questions/694200/linq-aggregate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!