David North
David North

Reputation: 1406

LINQ to SQL, aggregation of sub-query result

Assume the following simple table design:

Table Master (Id bigint PK, Message nvarchar(50))

Sample row in Master
101, "Foo"

Table Detail (Id bigint PK, MasterId bigint FK to Master PK, Code nvarchar(5))

Sample rows in Detail
1001, 101, "A"
1002, 101, "B"
1003, 101, "C"

Desired output from L2S query would be something like the following-

Id, Code(s), Message
101, "A, B, C", "Foo"

The following L2S query gives me what I want, but is there a better way to express it?

from m in Master
    where m.Id == 101
    select new
    {
       mi.Id,
       Codes = string.Join(",", (from c in Detail 
                                     where c.MasterId == m.Id
                                     select c.Code).ToArray()),
       mi.Message
    }

Upvotes: 0

Views: 163

Answers (1)

Darek
Darek

Reputation: 4797

Purrrrfect. I'd do same, except use method syntax. Seems more "natural" to me.

Upvotes: 1

Related Questions