简体   繁体   中英

LINQ - Group by one column and Count() rows (extension method)

I have a database that looks like this:

ID DocumentName Name
1 Test1.txt Alan
2 Test2.txt Alan
3 Test3.txt Jane
4 Test4.txt Alan
5 Test5.txt Bob

Now I want to use a LINQ query that will give me this result, using a key of name and the count of the rows per name:

Name Count
Alan 3
Jane 1
Bob 1

Please can you answer using extension methods? I feel like I am missing something simple, but I can't seem to find the answer.

Not much to it really, a GroupBy and then a projection to an anonymous type using Select .

var result = db.DocumentTable.GroupBy(t => t.Name)
                             .Select(g => new {
                                            Name = g.Key,
                                            Count = g.Count()
                                          }
                                    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM