2015-04-08 74 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中將這個函數重載。總之,非常感謝。 –