我有两个列表
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 | TotalValue = 38.24
LINQ to SQL LINQ to Objects
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”。
在这种情况下,如何按顺序过滤?
答案 0 :(得分:6)
试试这个:
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>
就足够了。此外,这还将为“商店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
});