'Update List element if object member is the smallest element in C#
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.
Solution 1:[1]
var item = data.OrderBy(x => x.age).First();
item.name = "some name";
Solution 2:[2]
var minAge = data.Min(a => a.age);
var dataWithMinAge = data.Where( a => a.age == minAge);
dataWithMinAge.Name = "Update to new value";
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Emin Mesic |
| Solution 2 | Smitha Kalluz |
