views:

38

answers:

1

I'm still trying to get the hang of LINQ and am having trouble with this. I have a List<Data> like so:

GroupId|SectionId|Content
-------------------------
      1|        3|part1-2
      1|        7|part1-1
      3|        3|part3-2
      1|        1|part1-3
      3|        1|part3-3
      3|        7|part3-1

I would like to convert it to IEnumerable<AnonymousType> where each AnonymousType represents one GroupId and each property is linked to a specific SectionId. In other words, you would end up with something like this:

{
  {
    GroupId = 1,
    Part1 = "part1-1", // From SectionId == 7
    Part2 = "part1-2", // From SectionId == 3
    Part3 = "part1-3", // From SectionId == 1
  },
  {
    GroupId = 3,
    Part1 = "part3-1", // From SectionId == 7
    Part2 = "part3-2", // From SectionId == 3
    Part3 = "part3-3", // From SectionId == 1
  }
}
+3  A: 

Like this:

 from r in something
 group r by r.GroupId into g
 select new {
      GroupId = g.Key,
      Part1 = g.First(r => r.SectionId == 7).Content,
      Part2 = g.First(r => r.SectionId == 3).Content,
      Part3 = g.First(r => r.SectionId == 1).Content
 }
SLaks
Great, they shut down our database for "maintenance" so I can't test it. I had everything up to g.Key. I keep forgetting g "contains" all the group's items, so this should work. I think I'll use `.Single(...)` instead of `.First(...)` in case I unexpectedly have more than one result, in which case I prefer to quit instead of having "undefined" behavior.
Nelson
I'm not sure if the `First` or `Single` calls will work in LINQ-to-SQL.
SLaks
This is LINQ-to-Objects anyway, so no worries. P.S. You seem to like LINQ since you show up in most of the LINQ question I have. :)
Nelson