Reputation: 4562
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
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