LINQ分组和选择属性

时间:2010-07-02 14:10:08

标签: c# linq linq-to-objects

我仍然试图抓住LINQ,我遇到了麻烦。我有List<Data>这样:

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

我想将其转换为IEnumerable<AnonymousType>,其中每个AnonymousType代表一个GroupId,每个属性都链接到特定的SectionId。换句话说,你最终会得到这样的东西:

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

1 个答案:

答案 0 :(得分:3)

像这样:

 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
 }