2017-08-24 36 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

哇!这真的很好!我没有想到将它转换为属性名称为属性值的中间字典。谢谢!! –

相关问题