c# - 如何在 LINQ 表达式中使用 group 对字段的子字符串进行分组?

标签 c# .net linq

跟进我的同事,我有以下类(class):

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

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

Error 1 Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

最佳答案

这应该会让你明白:

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 上观看实时演示

关于c# - 如何在 LINQ 表达式中使用 group 对字段的子字符串进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8308823/

相关文章:

.net - 如何从docker容器中的bash检查.net核心dll的版本

c# - LINQ 查询具有连接的列的平均值,按连接表的键分组

C# 平台调用,具有引用和值类型的 C 风格 union

c# - 对于一个 EDMX 文件,使用与多个数据库相关的多个连接字符串

c# - 桌面通知,又名内部警报系统

c# - 各种 MSBuild 版本属性(例如 Version、VersionPrefix 和 VersionSuffix)之间有什么区别?

c# XDocument问题

c# - 字符串编码和内存管理

c# - 取消缩进存储在字符串中的代码行的有效方法

c# - 多个 Linq 函数作为参数