跟进我的同事,我有以下类(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/