所有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
哇!这真的很好!我没有想到将它转换为属性名称为属性值的中间字典。谢谢!! –