2016-10-21 36 views
0

的我有很多在以下格式的數據..前5和另一列前五名每個第一列

var data1 = new[] { 
    new { Product = "Product 1", Year = 2009, Sales = 1212 }, 
    new { Product = "Product 2", Year = 2009, Sales = 522 }, 
    new { Product = "Product 1", Year = 2010, Sales = 1337 }, 
    new { Product = "Product 2", Year = 2011, Sales = 711 }, 
    new { Product = "Product 2", Year = 2012, Sales = 2245 }, 
    new { Product = "Product 3", Year = 2012, Sales = 1000 } 
}; 

如果我想獲得前20行,最大的銷售,我可以做一些如下...

data1.OrderByDescending(o=>o.Sales).Take(20); 

但我想要做的是獲得前5名產品和(對於那些產品)前5年隨着他們的銷售。

因此,輸出會像下面的東西:

var outputdata = new[] { 
    new { Product = "Product 1", Year = 2012, Sales = 2245 }, 
    new { Product = "Product 1", Year = 2010, Sales = 1337 }, 
    new { Product = "Product 1", Year = 2009, Sales = 1212 }, 
    new { Product = "Product 1", Year = 2011, Sales = 711 }, 
    new { Product = "Product 1", Year = 2013, Sales = 522 }, 
    new { Product = "Product 2", Year = 2012, Sales = 1000 } 
}; 

This可能是SQL類似的問題。但不幸的是無法理解如何轉換爲LINQ。

+0

的你能不能顯示輸出的例子嗎? –

+0

輸出結果與輸入相同 - {Product =「Product 1」,Year = 2009,Sales = 1212},如果您的問題是其他內容,請再次詢問,謝謝 – Arnab

+0

我的意思是可以用一個例子來說明想要的輸出? –

回答

1

好的,如果我理解正確:第一組由product,所以你可以訂購的產品總數sales。 然後你可以只採取你想要的金額。使用SelectMany扁平化組:

var data = new[] { 
      new { Product = "Product 1", Year = 2009, Sales = 1212 }, 
      new { Product = "Product 2", Year = 2009, Sales = 522 }, 
      new { Product = "Product 1", Year = 2010, Sales = 1337 }, 
      new { Product = "Product 2", Year = 2011, Sales = 711 }, 
      new { Product = "Product 2", Year = 2012, Sales = 2245 }, 
      new { Product = "Product 3", Year = 2012, Sales = 1000 } 
     }; 
int numberOfProducts = 2; 
int numberOfYearsForEachProduct = 3; 

var result = data.GroupBy(x => x.Product) 
    .OrderByDescending(x => x.Sum(y => y.Sales)) //Order products by their total sum of `Sales` 
    .Take(numberOfProducts) 
    .SelectMany(x => x.OrderByDescending(y => y.Sales).Take(numberOfYearsForEachProduct)) // Take only the N top years for each product 
    .ToList(); 

我在Take使用更小的數字,所以我可以看到它正在做正確

+0

是的,我想下一個訂購也在銷售.. – Arnab

+1

@Arnab - 更新了答案。很高興幫助你 –

0

如果我讓你正確的,你想獲得前20名的銷售爲前5名產品。

var ord = data1.OrderByDescending(o => o.Sales) 
       .Select(o => o.Product) 
       .Distinct().Take(5);//Get top 5 products by their sales 

var salesForTopProducts = data1.OrderByDescending(o => o.Sales) 
           .Where(o => ord.Contains(o.Product)) 
           .Take(20);//Get top 20 sales for top 5 products 
1

首先,你應該得到的20個最暢銷的產品

var top20Products = data1 
    .GroupBy(x => x.Product) 
    .OrderByDescending(group => group.Sum(x => x.Sales)) 
    .Select(group => group.Key) 
    .Take(20); 

,然後選擇前5個最暢銷的年他們

var top5yearsOfTop20products = top20Products 
    .SelectMany(product => data1 
     .Where(x => x.Product == product) 
     .OrderByDescending(x => x.Sales) 
     .Take(5)); 
相關問題