2016-10-22 37 views
0

我有兩個陣列..從一個列表只有那些存在於另一個和秩序由第二列表中選擇 - LINQ

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 } 
    }; 

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

我通過Product要組data1Sales僅做團體的總和那些存在於data2中的產品並以與它們在data2中相同的方式訂購它們。請注意,即使產品存在於data2中,該產品的data1中的所有年份都不存在於data2(例如{ Product = "Product 2", Year = 2009, Sales = 522 })中,因此分組和總和將必須發生在data1上。

只是做分組和總結以下應該工作..

data1.GroupBy(x=>x.Product) 
.Select(x=>new {Product=x.Key,Total= x.Sum(s=>s.Sales)}) 

但是我怎麼保證我的數據2只選擇產品,如數據2由Product責令結果

回答

1

我會採取不同的方法。

由於您希望最終結果包含第二個列表中的產品,因此我會從第二個列表中獲得Distinct產品。

儘管未在文檔中明確說明,該Distinct方法(類似於GroupBy)產生在源的獨特元件,所述Distinct的,因此結果的第一次出現的順序將是產品的不同元件最終結果以正確的順序排列。

然後我會用GroupJoin將其與第一列表關聯,具有非常高效的查詢結束了:

var result = data2.Select(item => item.Product).Distinct() 
    .GroupJoin(data1, product => product, item => item.Product, (product, group) => 
     new { Product = product, Sales = group.Sum(item => item.Sales) }) 
    .ToList(); 
1

您需要有兩件事:首先,您從data2中選擇可用的產品。爲此,您可以使用Select的過載,它也給出了匹配元素的索引。

其次,您根據data2中的產品篩選data1,然後執行分組。作爲最後一步,您需要添加一個與data2中的產品索引相匹配的新屬性CorrespondingIndex。該索引可用於根據data2中的產品訂購來訂購data1列表。

var productsWithIndex = data2 
    .Select(x => x.Product) 
    .Distinct() 
    .Select((p, idx) => new {Product = p, Index = idx}); 

    var filteredProducts = data1 
    .Where(x => productsWithIndex.Select(p => p.Product).Contains(x.Product)) 
    .GroupBy(x => x.Product) 
    .Select(x => new 
    { 
     Product = x.Key, 
     Total = x.Sum(s => s.Sales), 
     CorrespondingIndex = productsWithIndex.Single(p => p.Product == x.Key).Index 
    }) 
    .OrderBy(x => x.CorrespondingIndex); 
0

也許你甚至不需要去那麼多的細節,因爲user1384848去了。 你可能的東西,因爲這更簡單的相處:

var result = 
       data1.Where(e => data2.Any(x => x.Product == e.Product)) 
        .GroupBy(arg => arg.Product, 
         (name, products) => new {Product = name, Total = products.Sum(e => e.Sales)}) 
        .OrderBy(d => d.Product); 
+0

將這種不受DATA1產品訂單訂購吧 – Arnab

相關問題