davy
davy

Reputation: 4562

Returning an object of values from grouped LINQ statement

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?

Upvotes: 1

Views: 51

Answers (1)

Anirudha
Anirudha

Reputation: 32807

It should be

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

This is because group won't always have 2 elements with it..It's better you store those as a list

Upvotes: 1

Related Questions