MrScf
MrScf

Reputation: 2497

Define dynamic the properties of an anonymous type

I have a dictionary with a key and as value an IEnumerable.

var rowsByMonth = dictionaryByMonth.Select(item => new
{
    Station = item.Key.DisplayName,
    Month1 = item.Value.FirstOrDefault(element => element.ColumnIndex == 0),
    Month2 = item.Value.FirstOrDefault(element => element.ColumnIndex == 1),
    Month3 = item.Value.FirstOrDefault(element => element.ColumnIndex == 2),
    Month4 = item.Value.FirstOrDefault(element => element.ColumnIndex == 3)
});

The question is how can I create dynamically the properties Month1, Month2,...depending on the amount of the different ColumnIndex. Maybe I can have elements with different ColumnIndex. The ColumnIndexes are variable. I need to have an anonymous type with defined properties because I want to bind it to a DataGrid

Upvotes: 0

Views: 56

Answers (1)

Kien Chu
Kien Chu

Reputation: 4895

I hope I understood your question correctly

I think you need to use Tuple because you need flexible data structure

Link: https://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx

Sample:

var population = Tuple.Create(item.Key.DisplayName, item.Value.FirstOrDefault(element => element.ColumnIndex == 0), etc, etc);

And then you can get population.Item1, population.Item2, etc

Upvotes: 1

Related Questions