linq select 使用反射

linq select using reflection

我有一个这样的class,一个class列表,一个字符串列表

class Test
{
    public string AAA{ get; set; }
    public string BBB{ get; set; }
}

List<Test> test;

List<List<string>> output;

我想把测试的内容输出。 我现在使用 linq 来传输它,如下所示。

output[0] = test.Select(x=>x.AAA).ToList();
output[1] = test.Select(x=>x.BBB).ToList();

如果这个class有10个属性,我必须写10行代码来传递它。 我有一个关键字 "reflection" 但我不知道如何在我的代码中使用它。 任何建议将不胜感激。

这应该适用于所有字符串属性:

        List<List<string>> output = new List<List<string>>();
        foreach(var property in typeof(Test).GetProperties(
            BindingFlags.Public | BindingFlags.Instance))
        {
            if (property.PropertyType != typeof(string)) continue;

            var getter = (Func<Test, string>)Delegate.CreateDelegate(
                typeof(Func<Test, string>), property.GetGetMethod());
            output.Add(test.Select(getter).ToList());
        }

还算不错,我不觉得:

var allObjects = new List<Test>();
var output = new List<List<string>>();

//Get all the properties off the type
var properties = typeof(Test).GetProperties();

//Maybe you want to order the properties by name?
foreach (var property in properties) 
{
    //Get the value for each, against each object
    output.Add(allObjects.Select(o => property.GetValue(o) as string).ToList());
}

您可以请求所有具有反射的属性作为 List 和 select 来自 class 列表的属性,如下所示:

第一个将为每个 class 提供 1 个列表,其中包含属性列表和值

var first = test.Select(t => t.GetType().GetProperties().ToList().Select(p => p.GetValue(t, null).ToString()).ToList()).ToList();

这个会给你 1 个列表,每个 属性 列表 class 属性 值

var second typeof(Test).GetProperties().Select(p => test.Select(t => p.GetValue(t, null).ToString()).ToList()).ToList();