2017-08-24 34 views
2

我想動態地創建一個字典,其中的鍵將是一個對象的屬性的名稱,並且該值將是選擇該屬性的linq查詢的結果。有沒有辦法使用linq來循環對象列表的屬性?

MyObject[] records = getRecords(); 
foreach (property in MyObject.GetType().GetProperties()) 
{ 
    data[property.Name] = records.Select(r => new { x = r.Date.ToString(), y = r.propertyInfo}).ToArray(); 
} 

回答

8

你需要使用更多的反思:

property.GetValue(r) 

您還應該使用ToDictionary()

data = typeof(MyObject).GetProperties().ToDictionary(p => p.Name, p => ...) 
0

所有MyObject首先是一個類,而不是一個對象。 GetType()MyObject的非靜態函數,因此,只有在創建new Myobject()後,我們才能調用,我假設您要使用typeof(MyObject)

  • 首先,我們爲MyObject類的所有公共可讀屬性創建PropertyInfo對象的序列。
  • 然後對於每個propertyInfo,我們創建記錄中每個MyObject的屬性值序列。
  • 最後我們把序列中的一個字典

注意,同時創造小步查詢,沒有什麼是列舉,僅查詢被創建。只有GetPropertiesToDictionary會列舉。

IEnumerable<MyObject> records = GetRecords(); 
IEnumerable<PropertyInfo> readableProperties= typeof(MyObject).GetProperties 
    .Where(property => property.CanRead); 

var propertyValues = readableProperties // for every property 
    .Select(propertyInfo => new   // create one new object of anonymous type 
{              
    PropertyName = propertyInfo.Name,  // with the name of the property 
    PropertyValues = records    // and a sequence of all values of this property 
     .Select(record => propertyInfo.GetValue(record)) 
} 

最後字典:關鍵是屬性名稱,值是propertyValues的序列:

var result = propertyValues  // put every item in the collection of propertyValues 
    .ToDictionary(    // into a dictionary 
    item => item.PropertyName, // Key is the PropertyName of each item 
    item => item.PropertyValues); // Value is the sequence of PropertyValues of each item 
+0

哇!這真的很好!我沒有想到將它轉換爲屬性名稱爲屬性值的中間字典。謝謝!! –

相關問題