Home > Blockchain >  How to set Properties in a List with Grouping
How to set Properties in a List with Grouping

Time:11-04

I have a List<MyObject>.

public class MyObject
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateTime { get; set; }
    public decimal Value { get; set; }
    public decimal ValueToCalculate { get; set; }
}

The ValueToCalculate is not set yet.

How can I set the ValueToCalculate by the Value of the minimum DateTime grouped by FirstName and LastName.

I've tried various versions with GroupBy/MaxBy/SelectMany and whatever without success.

CodePudding user response:

First do the grouping, then find the object with the minimum date in each group to get the value from and finally update the objects in this group with this value

var groups = list
    .GroupBy(o => (o.FirstName, o.LastName));
foreach (var group in groups) {
    decimal value = group
        .OrderBy(o => o.DateTime)
        .First().Value;
    foreach (MyObject item in group) {
        item.ValueToCalculate = value;
    }
}

I build a tuple with the first and last names as group key to make grouping by the two properties possible.

Each group is an enumerable of MyObject we can enumerate to get the objects belonging to this group. To get the object with the minimum DateTime I order the objects by this DateTime and get the first one from which I extract the Value.

It is often easier to do the things step by step instead of trying to merge everything into a single unreadable LINQ query just to save 2 lines of code.

  • Related