Home > database >  Update List element if object member is the smallest element in C#
Update List element if object member is the smallest element in C#

Time:01-27

I have the following class.

public class DataDescr
{
    public string name { get; set; }
    public double age{ get; set; }
}

And I have the following List, containing elements of type DataDescr

List<DataDescr> data = new List<DataDescr>();

data.add(new DataDescr{ name = "Test_1", age = 20 });
data.add(new DataDescr{ name = "Test_2", age = 40 });
data.add(new DataDescr{ name = "Test_3", age = 10 });
data.add(new DataDescr{ name = "Test_4", age = 15 });

My goal is to update the value of name in the list of the element that has the lowest age value.

I have tried some approaches but nothing worked so far. Any help would be much appreciated.

CodePudding user response:

var item = data.OrderBy(x => x.age).First();
item.name = "some name";

CodePudding user response:

Please try this.

var minAge = data.Min(x => x.Age);
data.Where(x => x.Age == minAge).ToList().ForEach(x => { x.Name = "NEW_VALUE"; });
  •  Tags:  
  • Related