最简单的方法是使用ConvertAll
:
myList = myList.ConvertAll(d => d.ToUpper());
ForEach
与循环原始列表ConvertAll
并创建一个您需要重新分配的新列表没有太大区别。
var people = new List<Person> {
new Person { FirstName = "Aaa", LastName = "BBB", Age = 2 },
new Person{ FirstName = "Deé", LastName = "ève", Age = 3 }
};
people = people.ConvertAll(m => new Person
{
FirstName = m.FirstName?.ToUpper(),
LastName = m.LastName?.ToUpper(),
Age = m.Age
});
回答您的更新
我不想逐场循环或逐场进行。有没有办法通过反射将每个属性的值大写?
如果您不想逐场循环或逐场进行。你可以使用类上的属性来给你大写,就像这样
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string FirstNameUpperCase => FirstName.ToUpper();
public string LastNameUpperCase => LastName.ToUpper();
}
或者你可以像这样使用后场
public class Person
{
private string _firstName;
public string FirstName {
get => _firstName.ToUpper();
set => _firstName = value;
}
private string _lastName;
public string LastName {
get => _lastName.ToUpper();
set => _lastName = value;
}
public int Age { get; set; }
}