开发者

When using Linq's 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 to create a list of groups based on the first letter of a book's title, then display all the books in the group below each particular letter. So for example, if the current letter was "C" I would want to select the group where its key was also "C". I thought running a query to create the groups would be more efficient than running a query for each letter, but I'm running in problems.

Here's how I create the group (sorry for the VB) (Model is 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 through 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, it doesn't work:

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

I can't seem to work with any of the properties I expect on CurrentGroup. I have also tried "Select Grp.Group", which also doesn't seem to help.

Any suggestions would be appreciated!

UPDATE:

em's answer below proved correct, but I thought I'd share the code after translation 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/>")开发者_如何学JAVA
    Next
Next


You have to explicitly define your projection (ie. "pack" your group). Some useful LINQ code samples are available here.

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

var books = new[] { new Book("A book"),
    new Book("Your Book"),
    new Book("My book"),
    new Book("Anne's 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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜