Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Array Objects into another using LINQ?

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.

like image 337
Kishor Patil Avatar asked Mar 22 '26 20:03

Kishor Patil


1 Answers

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}
                                 });
like image 162
KeithS Avatar answered Mar 25 '26 09:03

KeithS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!