When using Linq GROUP BY to create a list of groups, how can I select a specific group by its key?

What I'm trying to do here is create a list of groups based on the first letter of the book’s name, and then display all the books in the group under each specific letter. So, for example, if the current letter was “C”, I would like to select a group where its key was also “C”. I thought running a query to create groups would be more efficient than running a query for each letter, but I ran into problems.

This is how I create a group (sorry for VB) (Model defined as IEnumerable (of Book):

Dim TitleGroups = From Bk In Model Group Bk By Bk.FirstLetter Into Group Order By FirstLetter 

If I then take TitleGroups and iterate over it, everything works fine:

 For Each Grp In TitleGroups Resposnse.Write(Grp.FirstLetter & "<br/>") For Each Bk In Grp.Group Response.Write(Bk.Title & "<br/>") Next Next 

But if I try to select a group, this will not work:

 Dim CurrentGroup = From Grp In TitleGroups Where Grp.FirstLetter = "A" Select Grp 

I cannot work with any properties that I expect from CurrentGroup. I also tried "Choose Grp.Group", which also does not help.

Any suggestions would be appreciated!

UPDATE:

The em answer below proved to be correct, but I thought I would pass the code after translating to VB (don't judge me):

 Dim TitleGroups = From Bk In Model _ Order By Bk.FirstLetter _ Group Bk By Bk.FirstLetter Into Books = Group, BkGrp = AsEnumerable() _ Select FirstLetter, Books Dim CurrentGroup = From Grp In TitleGroups _ Where Grp.FirstLetter = "A" _ Select Grp For Each Grp In CurrentGroup Response.Write(Grp.FirstLetter & "<br/>") For Each Book In Grp.Books Response.Write(Bk.Title & "<br/>") Next Next 
+4
source share
1 answer

You must explicitly define your projection (for example, the "package" of your group). There is some useful LINQ samples code here.

see below for the working version of your C # code:

 var books = new[] { new Book("A book"), new Book("Your Book"), new Book("My book"), new Book("Anne book") }; var titleGroups = from book in books orderby book.FirstLetter group book by book.FirstLetter into bookGroup select new {FirstLetter = bookGroup.Key, Books = bookGroup}; var currentGroup = from Grp in titleGroups where Grp.FirstLetter == "A" select Grp.Books; foreach (var group in currentGroup) { Console.WriteLine(group.Key); // First letter foreach (var book in group) { Console.WriteLine(book.Title); } } 
+3
source

Source: https://habr.com/ru/post/1337416/


All Articles