Samantha J T Star
Samantha J T Star

Reputation: 32798

How can I use group in a LINQ expressions to group substrings of a field?

Following up for my workmate I have the following class:

public Pages {
  primary_key { get; set; }
}

Data for the primary key looks like this:

010000100001
010000100001
010000100001
010000100002
010000100002
010000100002
010000200003
010000200003
020000300004
020000300005

I am trying to understand how I can group this data using LINQ. What I need to do is to group by:

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)

Every time the subject changes I need to get a count of how many chapters and how many books are in that subject.

There was a suggestion link this. It gives me some ideas but I am still left confused.

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

I tried to implement this as:

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

However I am getting an error message saying:

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

Upvotes: 3

Views: 5145

Answers (1)

sehe
sehe

Reputation: 392954

This should get you the idea:

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

Edit See a demo live on https://ideone.com/A6RQU

Upvotes: 4

Related Questions