gpt4 book ai didi

c# - 按字符串在对象列表中查找值

转载 作者:行者123 更新时间:2023-11-30 12:55:26 26 4
gpt4 key购买 nike

我需要从这样的对象列表中找到最长的值...

var longestValue = list.Max(x => x.Name);

问题是我不能像这样直接访问它,但这需要在循环中进行。这是我到目前为止所拥有的..

        public static void SetPropertyValue(this object obj, string propName, object value)
{
obj.GetType().GetProperty(propName).SetValue(obj, value, null);
}


var user = new User();

var list = new List<User>
{
new Svedea {Name = "Steve", Car = "Volkswagen"},
new Svedea {Name = "Denice Longhorn", Car = "Tesla"},
new Svedea {Name = "Rebecca", Car = "Ford"},
new Svedea {Name = "Mike O", Car = "Mercedes-Benz"}
};

var properties = user.GetType().GetProperties();
var propList = properties.Select(pi => pi.Name).ToList();

var newUser = new User();

foreach (var row in propList)
{
// Here I need to find the longest value from the list above like this...
// var longestValue = list.Max(x => x.row); // This is obviously not correct but I need to find this value needs to be found dynamically

var longestValue = list.Max(x => x.row);
newUser.SetPropertyValue(row, longestValue);

}

最佳答案

使用 LINQ OrderByDescendingName 的最长值和 Car 的最长值对列表进行排序。然后您可以创建一个新的用户 longestUser,它具有最长的 NameCar 值:

var longestName = list.OrderByDescending(x => x.Name.Length).First().Name;
var longestCar = list.OrderByDescending(x => x.Car.Length).First().Car;
var longestUser = new User() { Name = longestName, Car = longestCar };

最长用户:

Name = "Denice Longhorn"

汽车 = "奔驰"

编辑:

我修改了上面的解决方案,以便您可以使用字符串值访问属性名称:

var longestNameUser = list.OrderByDescending(x => x.GetType().GetProperty("Name").GetValue(x, null).ToString().Length).First();
var longestName = longestNameUser.GetType().GetProperty("Name").GetValue(longestNameUser, null);

var longestCarUser = list.OrderByDescending(x => x.GetType().GetProperty("Car").GetValue(x, null).ToString().Length).First();
var longestCar = longestCarUser.GetType().GetProperty("Car").GetValue(longestCarUser, null);

var newUser = new User();
PropertyInfo propertyInfo;

propertyInfo = newUser.GetType().GetProperty("Name");
propertyInfo.SetValue(newUser, Convert.ChangeType(longestName, propertyInfo.PropertyType), null);

propertyInfo = newUser.GetType().GetProperty("Car");
propertyInfo.SetValue(newUser, Convert.ChangeType(longestCar, propertyInfo.PropertyType), null);

您修改的 for 循环:

var newUser = new User();
PropertyInfo propertyInfo;

foreach (var row in propList)
{
var longestValueUser = list.OrderByDescending(x => x.GetType().GetProperty(row).GetValue(x, null).ToString().Length).First();
var longestValue = longestValueUser.GetType().GetProperty(row).GetValue(longestValueUser, null);
propertyInfo = newUser.GetType().GetProperty(row);
propertyInfo.SetValue(newUser, Convert.ChangeType(longestValue, propertyInfo.PropertyType), null);
}

关于c# - 按字符串在对象列表中查找值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49768895/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com