1

I have successfully got my desired output from a grouped LINQ statement but I'm wondering if there is a more elegant way.

At the moment I have two elements in each group and I'm using the code below to return a list of objects with fieldA, fieldB values:

infoList.GroupBy(s => s.Name.Substring(0, s.Name.LastIndexOf("whatever")) + 1)
         .Select(grp => new { 
                              fieldA = grp.ElementAt(0).Value, 
                              fieldB = grp.ElementAt(1).Value 
                         }
          );

can anyone help please?

4

1 回答 1

1

它应该是

infoList.GroupBy(s => s.Name.Substring(0, s.Name.LastIndexOf("whatever"),
                (key, g) => new { fieldKey= key,fieldValues = g.ToList() });

这是因为 group 并不总是有 2 个元素。最好将它们存储为列表

于 2013-09-30T12:17:27.860 回答