Reputation: 31
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.
Upvotes: 3
Views: 1491
Reputation: 7915
Starting from KeithS answer you could group this by months:
var results = from x in KeithsAnswer
group x by x.Month into g
select new { Month = g.Key, CategoryValues = g.Select(c => new { c.Month, c.Val }).ToArray()};
You can pass this directly to the client to process there or if you really need the form you specified above, you can implement your own JavaScriptConverter
or use a dynamic/ExpandoObject to store the values as properties.
Upvotes: 0
Reputation: 71591
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}
});
Upvotes: 2