0

I have a list which itself contains n lists (in this instance there are 4). What I need to do is get an output as in 'required query result' below

List of lists:

Product      Year    DY
Comp         1992    110.0 
Comp         1993    200.0 
Non-Comp     1990    45.2 
Non-Comp     1991    50.0 
Non-Comp     1992    55.0 
Non-Comp     1993    100.0 

Product      Year    DY
Comp         1992    170.0 
Non-Comp     1990    64.8 
Non-Comp     1991    75.0 
Non-Comp     1992    85.0 

Product      Year    DY
Non-Comp     1991    25.0 

Product      Year    DY
Non-Comp     1990    37.0 

Required query result:

Product      Year    DY1     DY2     DY3     DY4
Comp         1992    110.0  170.0       
Comp         1993    200.0          
Non-Comp     1990    45.2   64.8             37.0
Non-Comp     1991    50.0   75.0     25.0   
Non-Comp     1992    55.0   85.0        
Non-Comp     1993    100.0  

Remember there could be more than 4 lists in the list so I have imagined something like:

foreach (var element in myList)
{
    // some hard work
}
descf
  • 1,302
  • 1
  • 12
  • 31

3 Answers3

1

It's hard to answer this without a better description of your input/output object-model, but I think you want to:

  1. Flatten your list of lists of item into a single (flat) sequence of items.
  2. Group those items with a complex key comprising an item's Product and Year.
  3. Project the items in each group to their respective DYs.

Something like:

var query = myListOfLists.SelectMany(list => list) // Flatten
                         .GroupBy(item => new { item.Product, item.Year }, // Group
                                  item => item.DY); // Project
Ani
  • 111,048
  • 26
  • 262
  • 307
0

I think you can do it by using LINQ

Please check the following link:

Is it possible to Pivot data using LINQ?

Community
  • 1
  • 1
Scorpion
  • 4,495
  • 7
  • 39
  • 60
0

Something like this?

List<List<Product>> nestedList;

List<Product> = allProducts = nestedList.SelectMany(x => x);
var groupped = allProducts
  .GroupBy(x => new { Product = x.Product, Year = x.Year}, x => x.DY );
Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193