所有MyObject
首先是一個類,而不是一個對象。 GetType()
是MyObject
的非靜態函數,因此,只有在創建new Myobject()
後,我們才能調用,我假設您要使用typeof(MyObject)
。
- 首先,我們爲
MyObject
類的所有公共可讀屬性創建PropertyInfo
對象的序列。
- 然後對於每個propertyInfo,我們創建記錄中每個
MyObject
的屬性值序列。
- 最後我們把序列中的一個字典
注意,同時創造小步查詢,沒有什麼是列舉,僅查詢被創建。只有GetProperties
和ToDictionary
會列舉。
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
哇!這真的很好!我沒有想到將它轉換爲屬性名稱爲屬性值的中間字典。謝謝!! –