So basically what you want, is to divide your data elements into groups with the same value for GroupName
. From every group you want to take one element, namely the one with the largest value for property MemberValue
.
Whenever you have a sequence of items, and you want to divide this sequence into groups based on the value of one or more properties of the items in the sequence you use Enumerable.GroupBy
'GroupBy' takes your sequence as input and an extra input parameter: a function that selects which properties of your items you want to compare in your decision in which group you want the item to appear.
In your case, you want to divide your sequence into groups where all elements in a group have the same GroupName
.
var groups = mySequence.GroupBy(element => element.GroupName);
What it does, it takes from every element in mySequence the property GroupName, and puts this element into a group of elements that have this value of GroupName.
Using your example data, you'll have three groups:
- The group with all elements with GroupName == "Group1". The first two elements of your sequence will be in this group
- The group with all elements with GroupName == "Group2". The third and fourth element of your sequence will be in this group
- The group with all elements with GroupName == "Group3". The last two elements of your sequence will be in this group
Each group has a property Key, containing your selection value. This key identifies the group and is guaranteed to be unique within your collection of groups. So you'll have a group with Key == "Group1", a group with Key == "Group2", etc.
Besides the Key
, every group is a sequence of the elements in the group (note: the group IS an enumerable sequence, not: it HAS an enumerable sequence.
Your second step would be to take from every group the element in the group with the largest value for MemberValue
. For this you would order the elements in the group by descending value for property MemberValue and take the first one.
var myResult = mySequence.GroupBy(element => element.GroupName)
// intermediate result: groups where all elements have the same GroupName
.Select(group => group.OrderByDescending(groupElement => groupElement.MemberValue)
// intermediate result: groups where all elements are ordered in descending memberValue
.First();
Result: from every group ordered by descending memberValue, take the first element, which should be the largest one.
It is not very efficient to order the complete group, if you only want the element with the largest value for memberValue. The answer for this can be found
here on StackOverflow