Reputation: 11
I want to dynamically create a dictionary where the key will be the name of a property of an object, and the value would be the result of a linq query selecting that property.
MyObject[] records = getRecords();
foreach (property in MyObject.GetType().GetProperties())
{
data[property.Name] = records.Select(r => new { x = r.Date.ToString(), y = r.propertyInfo}).ToArray();
}
Upvotes: 2
Views: 1812
Reputation: 30454
First of all MyObject
is a class, not an object. GetType()
is a non-static function of MyObject
, therefore you can only call if after you've created a new Myobject()
I assume you want to use typeof(MyObject)
.
PropertyInfo
objects for all public readable properties of class MyObject
.MyObject
in records. Note that while creating the query in small steps, nothing is enumerated, only the query is created. Only GetProperties
and ToDictionary
will enumerate.
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))
}
Finally to dictionary: key is the property name, value is the sequence of 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
Upvotes: 0
Reputation: 887225
You need to use more Reflection:
property.GetValue(r)
You should also use ToDictionary()
:
data = typeof(MyObject).GetProperties().ToDictionary(p => p.Name, p => ...)
Upvotes: 8