2013-12-20 110 views
-1

我有兩個列表LINQ - 集團加入+ Where子句

var stores = new[] 
{ 
    new { Code = 1, Name = "Store 1" }, 
    new { Code = 2, Name = "Store 2" }  
}; 

var orders = new[] 
{ 
    new { Code = 1, StoreCode = 1, TotalValue = 4.12 }, 
    new { Code = 2, StoreCode = 1, TotalValue = 14.12 }, 
    new { Code = 3, StoreCode = 1, TotalValue = 24.12 } 
}; 

輸出所需

STORENAME =存儲1 |總價值= 38.24

LINQ到SQL LINQ到對象

var result = (from s in stores 
       join o in orders on s.Code equals o.StoreCode into grp 
       where o.TotalValue > 10 // error 
       select new 
       { 
        StoreName = s.Name, 
        TotalValue = grp.Sum(x => x.TotalValue) 
       }).ToList(); 

錯誤: 'O' 不存在於當前上下文存在名稱。

在這種情況下,如何按順序過濾?

+5

刪除你的問題,並重新張貼,一字,只是因爲它已經得到了downvotes,是不恰當的,很可能會導致你在問問題被取締未來。 – Servy

+0

http://stackoverflow.com/questions/20707635/linq-group-join-and-where-clause#20707635 – Servy

+0

@Servy我不知道。抱歉! – user3122316

回答

5

試試這個:

var result = (from s in stores 
       join o in orders.Where(x => x.TotalValue > 10) on s.Code equals o.StoreCode into grp 
       select new 
       { 
        StoreName = s.Name, 
        TotalValue = grp.Sum(x => x.TotalValue) 
       }); 

或者這

var result = (from s in stores 
       join o in orders on s.Code equals o.StoreCode into grp 
       select new 
       { 
        StoreName = s.Name, 
        TotalValue = grp.Where(x => x.TotalValue > 10) 
            .Sum(x => x.TotalValue) 
       }); 

注意,它通常沒有必要調用ToList,因爲這需要查詢的立即評估。大多數情況下,將其作爲IEnumerable<T>就足夠了。此外,這也將返回一個'Store 2'的行,TotalValue = 0。如果你想要省略這些行,你可以使用這樣的東西。

var result = (from s in stores 
       join o in orders.Where(x => x.TotalValue > 10) on s.Code equals o.StoreCode into grp 
       let totalValue = grp.Sum(x => x.TotalValue) 
       where totalValue > 0 
       select new 
       { 
        StoreName = s.Name, 
        TotalValue = totalValue 
       }); 

或者這

var result = (from s in stores 
       join o in orders on s.Code equals o.StoreCode into grp 
       let totalValue = grp.Where(x => x.TotalValue > 10) 
            .Sum(x => x.TotalValue) 
       where totalValue > 0 
       select new 
       { 
        StoreName = s.Name, 
        TotalValue = totalValue 
       }); 
+0

好男人。 .. 謝謝! – user3122316