使用Linq的GROUP BY创建组列表时,如何通过其键选择特定组?

时间:2011-01-28 03:15:15

标签: linq asp.net-mvc-2 group-by

我在这里要做的是根据书名的第一个字母创建一个组列表,然后在每个特定字母下方显示该组中的所有书籍。因此,例如,如果当前字母是“C”,我想要选择其键也是“C”的组。我认为运行查询来创建组比为每个字母运行查询更有效,但我遇到了问题。

以下是我创建组的方法(对不起VB)(模型定义为IEnumerable(Book):

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

如果我接着使用TitleGroups并迭代它,一切正常:

For Each Grp In TitleGroups
    Resposnse.Write(Grp.FirstLetter & "<br/>")

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

但是如果我尝试选择一个组,它就不起作用了:

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

我似乎无法使用我期望在CurrentGroup上的任何属性。我也试过“选择Grp.Group”,这似乎也没有用。

任何建议都将不胜感激!

更新

下面的回答证明是正确的,但我认为在翻译成VB之后我会分享代码(不要评判我):

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

1 个答案:

答案 0 :(得分:3)

您必须明确定义您的投影(即“打包”您的组)。这里提供了一些有用的LINQ代码samples

请参阅下面的代码的C#版本:

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);
    }
}