如何在LINQ表达式中使用group来分组字段的子字符串?

时间:2011-11-29 09:56:46

标签: c# .net linq

跟随我的同事,我有以下课程:

public Pages {
  primary_key { get; set; }
}

主键的数据如下所示:

010000100001
010000100001
010000100001
010000100002
010000100002
010000100002
010000200003
010000200003
020000300004
020000300005

我试图了解如何使用LINQ对这些数据进行分组。我需要做的是 分组:

Column 1-2 (2 columns that I'll call subject)
Column 3-7 (5 columns that I'll call chapter)
Column 8-12 (5 columns that I'll call book)

每当主题发生变化时,我都需要计算该主题中有多少章和多少本书。

有一个建议链接。它给了我一些想法,但我仍然感到困惑。

from page in pages
group page by new { 
                    page.subjectId
                    , page.bookId
                    , page.chapterId 
                 } into group
select new {
             group.key.SubjectId
             , group.key.bookId
             , group.Key.chapterId
             , total = pages.sum(s => s.Page)
}

我试图将其实现为:

var a = from Page in rowData
    group /*Page*/ by new { 
       SubjectId = Page.PartitionKey.Substring(0,2),
       chapterId = Page.PartitionKey.Substring(2,6),
       bookId = Page.PartitionKey.Substring(8)
    } into group
select new {
    group.key.SubjectId
    , group.key.bookId
    , group.Key.chapterId
    , total = rowData.sum(s => s.Page)
};

但是我收到一条错误消息:

  

错误1无效的匿名类型成员声明符。必须使用成员分配,简单名称或成员访问声明匿名类型成员。

1 个答案:

答案 0 :(得分:3)

这可以让你明白:

new [] { 
    "010000100001", "010000100001", "010000100001", "010000100002",
    "010000100002", "010000100002", "010000200003", "010000200003",
    "020000300004", "020000300005" }
.GroupBy(s => new {
          Subject = s.Substring(0,2),
          Chapter = s.Substring(2,6),
          Book    = s.Substring(8) });

修改 https://ideone.com/A6RQU

上观看演示