linq选择使用反射

时间:2015-04-08 15:42:54

标签: c# linq reflection

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

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();

如果这个类有10个属性,我必须编写10行代码来传输它。 我有一个关键字“反射”,但我不知道如何在我的代码上使用它。 任何建议将不胜感激。

3 个答案:

答案 0 :(得分:0)

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

        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());
        }

答案 1 :(得分:0)

这不是太糟糕,我不认为:

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());
}

答案 2 :(得分:0)

您可以使用反射作为列表请求所有属性,并从类列表中选择以下内容:

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

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

这个将为每个属性提供1个列表,其中包含类属性值列表

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