Can any one tell me the linq query for this sql?
select
t1.item,
IsNull(sum(t2.price), 0) total
from table1 t1
left join table2 t2
on t1.id = t2.itemid
group by t1.item
LINQ version of your SQL query,
var resutl = from t1 in objtable1
join t2 in objtable2 on t1.id equals t2.itemid into j1
from j2 in j1.DefaultIfEmpty()
group j2 by t1.item into grouped
select new { item = grouped.Key, sum = grouped.Sum(t => t != null ? (t.price ??0 ) : 0) };
If you have value (id) in table1 but not in table2 (itemid) then t
inside grouped.Sum()
will be null so you need to check if t
is not null and t.price
also is not null inside grouped.sum()
Use it as
var result = (from t1 in table1
join t2 in table2 on t1.id equals t2.itemId
into t2d from td in t2d.DefaultIfEmpty()
group t1 by t1.item into t1g select new {item=t1g.key, sum =t1g.Sum(p=>p.price??0)} ).ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.