简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM