2015-04-08 78 views
1

我有这样一个类,一类List,字符串列表清单LINQ选择使用反射

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

要通过反射来这里做什么是非常复杂 - 一个高级的主题,因为:你周围泛型工作(泛型和反射效果不好),b:它涉及LINQ表达式树或代表。在这种情况下,这10行可能是一个更可维护的选项......你确定你想进入这个吗? –

+0

我有很多实体框架类。我想要插入大量数据到表中,我使用oracle数据绑定。因此,我应该为每个字段创建数组,以将值设置为OracleParameter.Value。该表可能有许多字段10,15。我只想简化我的代码 –

回答

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

propertyInfo.GetValue()至少有两个参数? –

+0

你不应该需要两个参数...该代码编译&为我工作,净4.5 –

+0

明白了,我使用的是.NET 4.0。微软在4.5中将这个函数重载。总之,非常感谢。 –