Linq GroupJoin 添加默认条目
Linq GroupJoin add default entries
var storeIds = repository.Get<Store>()
.Select(s => s.Id)
.ToList();
var storeReceipts = repository.Get<Receipt>()
.Where(r => DbFunctions.TruncateTime(r.LogDate) == today)
.GroupBy(r => r.StoreId)
.Select(g => new { Id = g.Key, Sales = g.Sum(r => r.TotalPrice) })
.GroupJoin(storeIds, x => x.Id, s => s, (x, s) => x ?? new { Id = s, Sales = 0 });
基本上我希望 GroupJoin 为任何没有收据记录的商店添加一个条目到序列中。
我上面的 ??
语法没有编译(即使编译了我也不确定它是否正确)。
如果你想连接两个表,你可能想试试这个。
var storeSales = from s in repository.Get<Store>()
join r in repository.Get<Receipt>() on s.Id equals r.StoreId into g
select new {
StoreId = s.Id,
Sales = g.Sum(x => (decimal?)x.TotalPrice) ?? 0
};
它首先从 Stores
中选择,这样您将获得每个商店的条目。接下来它将通过将商店 ID 匹配到一个将两者连接起来的组 g
来加入 Receipts
。
这允许您选择输出形状,每个商店一件商品。在这种情况下,商店的Id
为StoreId
,并且每个收据的TotalPrice
值的总和为Sales
。
如果商店没有收据,这笔金额最终将为 0。
var storeIds = repository.Get<Store>()
.Select(s => s.Id)
.ToList();
var storeReceipts = repository.Get<Receipt>()
.Where(r => DbFunctions.TruncateTime(r.LogDate) == today)
.GroupBy(r => r.StoreId)
.Select(g => new { Id = g.Key, Sales = g.Sum(r => r.TotalPrice) })
.GroupJoin(storeIds, x => x.Id, s => s, (x, s) => x ?? new { Id = s, Sales = 0 });
基本上我希望 GroupJoin 为任何没有收据记录的商店添加一个条目到序列中。
我上面的 ??
语法没有编译(即使编译了我也不确定它是否正确)。
如果你想连接两个表,你可能想试试这个。
var storeSales = from s in repository.Get<Store>()
join r in repository.Get<Receipt>() on s.Id equals r.StoreId into g
select new {
StoreId = s.Id,
Sales = g.Sum(x => (decimal?)x.TotalPrice) ?? 0
};
它首先从 Stores
中选择,这样您将获得每个商店的条目。接下来它将通过将商店 ID 匹配到一个将两者连接起来的组 g
来加入 Receipts
。
这允许您选择输出形状,每个商店一件商品。在这种情况下,商店的Id
为StoreId
,并且每个收据的TotalPrice
值的总和为Sales
。
如果商店没有收据,这笔金额最终将为 0。