大写带有LINQ的对象列表

Kri*_*s-I 1 c# linq

我有下面的代码.我想将此列表中的所有项目转换为大写.

在Linq有办法做到这一点吗?

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

public class MyClass
{
    List<Person> myList = new List<Person>{ 
        new Person { FirstName = "Aaa", LastName = "BBB", Age = 2 },
        new Person{ FirstName = "Deé", LastName = "ève", Age = 3 }
    };
}
Run Code Online (Sandbox Code Playgroud)

更新

我不想循环或逐字段去.有没有办法通过反射来大写每个属性的值?

ken*_*n2k 14

你为什么要使用LINQ?

用途List<T>.ForEach:

myList.ForEach(z =>
                {
                    z.FirstName = z.FirstName.ToUpper();
                    z.LastName = z.LastName.ToUpper();
                });
Run Code Online (Sandbox Code Playgroud)

编辑:不知道为什么你想通过反射这样做(我不会这样做...),但这里的一些代码将大写所有返回字符串的属性.请注意,它远非完美,但如果您真的想使用反射,它是您的基础......:

public class Person
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public int Age { get; set; }
}

public static class MyHelper
{
    public static void UppercaseClassFields<T>(T theInstance)
    {
        if (theInstance == null)
        {
            throw new ArgumentNullException();
        }

        foreach (var property in theInstance.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
        {
            var theValue = property.GetValue(theInstance, null);
            if (theValue is string)
            {
                property.SetValue(theInstance, ((string)theValue).ToUpper(), null);
            }
        }
    }

    public static void UppercaseClassFields<T>(IEnumerable<T> theInstance)
    {
        if (theInstance == null)
        {
            throw new ArgumentNullException();
        }

        foreach (var theItem in theInstance)
        {
            UppercaseClassFields(theItem);
        }
    }
}

public class Program
{
    private static void Main(string[] args)
    {
        List<Person> myList = new List<Person>{
            new Person { FirstName = "Aaa", LastName = "BBB", Age = 2 },
            new Person{ FirstName = "Deé", LastName = "ève", Age = 3 }
        };

        MyHelper.UppercaseClassFields<Person>(myList);

        Console.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)