简体   繁体   English

如果 object 成员是 C# 中的最小元素,则更新列表元素

[英]Update List element if object member is the smallest element in C#

I have the following class.我有以下 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我有以下列表,其中包含 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.任何帮助将非常感激。

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

Please try this.请试试这个。

var minAge = data.Min(x => x.Age);
data.Where(x => x.Age == minAge).ToList().ForEach(x => { x.Name = "NEW_VALUE"; });
var minAge = data.Min(a => a.age);
var dataWithMinAge = data.Where( a => a.age == minAge);
dataWithMinAge.Name = "Update to new value";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM