How can I convert array objects to another using LINQ?

I have a list of anonymous objects containing the following fields in C #, obtained 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 can I create a list of objects having one field for each category value (so there are essentially 12 objects one object for each month (jan, feb, march, etc.).

ExpectedResult {
string Month, 
decimal category1,
decimal category2,
decimal category3,
...
decimal categoryN
}

      

So the result will be 12 ExpectedResult objects. Not knowing how many categories / is a problem. Any quick suggestion would be helpful.

+3


source to share


2 answers


You can try the 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 anonymous source objects, this query will generate an array of 12 new anonymous objects, and then these arrays (as Enumerables) will be combined into one large collection.



To avoid string comparisons later, consider using Enum for 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}
                                 });

      

+2


source


Starting with KeithS answer, you can group this by month:

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 for processing there, or if you really need the form above, you can implement your own JavaScriptConverter

or use a dynamic / ExpandoObject to store the values ​​as properties.

0


source







All Articles