Anthony Farrisi
Anthony Farrisi

Reputation: 11

Is there a way to loop through properties of a list of objects using linq?

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

Answers (2)

Harald Coppoolse
Harald Coppoolse

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).

  • First we create the sequence of PropertyInfo objects for all public readable properties of class MyObject.
  • Then for every propertyInfo we create a sequence of value of the property of every MyObject in records.
  • Finally we put sequence in one dictionary

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

SLaks
SLaks

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

Related Questions