开发者

How do I extract and combine a list of n lists?

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  开发者_如何学Python   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
}


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


I think you can do it by using LINQ

Please check the following link:

Is it possible to Pivot data using LINQ?


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 );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜