I have a List of Anonymous objects containing following fields in C# derived from a LINQ query.
{
String category
decimal Jan
decimal Feb
decimal Mar
decimal Apr
decimal May
decimal Jun
decimal Jul
decimal Aug
decimal Sep
decimal Oct
decimal Nov
decimal Dec
}
how could I create a list of Objects having one field for each value of category ( so essentially 12 objects one object for each month( jan, feb, march etc.).
ExpectedResult {
string Month,
decimal category1,
decimal category2,
decimal category3,
...
decimal categoryN
}
So result would have 12 objects of ExpectedResult. Not knowing how many categories/is a problem. Any quick suggestion would be helpful.
You can try a SelectMany() method:
anonymousList.SelectMany(x=>new[]{
new {Cat=category, Month="Jan", Val=Jan},
new {Cat=category, Month="Feb", Val=Feb},
... ,
new {Cat=category, Month="Dec", Val=Dec}
});
For each of your source anonymous objects, this query will produce an array of 12 new anonymous objects, and then those arrays (as Enumerables) will be concatenated into one large collection.
Just to avoid comparing strings later on, consider using an Enum for the months of the year (unfortunately .NET doesn't have one built-in):
public enum Month
{
January = 1,
February = 2,
...
December = 12
}
...
anonymousList.SelectMany(x=>new[]{
new {Cat=category, Month=Month.January, Val=Jan},
new {Cat=category, Month=Month.February, Val=Feb},
... ,
new {Cat=category, Month=Month.December, Val=Dec}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With