I am learning Linq by reading Linq in Action book. On chapter 5 where the author performs multiple grouping. The linq expression is as follow:
var query =
from book in SampleData.Books
group new {book.Title, book.Publisher.Name} by book.Subject into grouping
select new {Subject=grouping.Key.Name, Books=grouping};
The output from author is:
I am rewriting by using operator instead of expression. I tried with this but the result showing in LinqPad is not the same as the above:
var query2 = SampleData.Books.GroupBy(
book => new {book.Subject}
)
.Select(book => new {
Subject = book.Key.Subject.Name,
Children = book.GroupBy(b => new {b.Subject.Description, b.Subject.Name})}
);
This is my output:
The first query performs a single groupBy, the second performs two nested groupBy.
To accurately represent the first query in method syntax, you need the overload of GroupBy that takes two parameters, one to pick the key for each element, and one to pick the representation of each element within the group
.GroupBy(book => book.Subject, book => new {book.Title, book.Publisher.Name} )
(Note that you do not need to create an anonymous object with only one member: book => book.Subject
works just as well as book => new{book.Subject}
Then you can perform the final select over the result of the GroupBy operator:
.Select(grouping => new {Subject=grouping.Key.Name, Books=grouping});
You can also do this all with only the GroupBy command, if you use this even more obscure GroupBy overload that takes three parameters: key-selector, element-selector and result-selector:
.GroupBy(book => book.Subject,
// select a key
book => new {book.Title, book.Publisher.Name},
// select the elements of each group
grouping => new {Subject=grouping.Key.Name, Books=grouping} )
// select the final result
This does exactly the same as the previous two commands combined.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句