我需要将 sql 转换为 Linq
I need to convert sql to Linq
这是我的 sql 命令:
select
b.Brand,
count(b.Brand) as BrandCount,
SUM(a.Qty) as DeviceCount
from (
select * from DeviceList
) as a
join DeviceMaster as b
on a.DeviceMasterId = b.Id
group by b.Brand
这是我到目前为止尝试过的方法:
var v1 = (from p in ghostEntities.DeviceMasters
join c in ghostEntities.DeviceLists on p.Id equals c.DeviceMasterId
select new table_Model {
Id = c.Id,
qty = c.Qty.Value,
month = c.DMonth,
brand = p.Brand,
model = p.Model,
memory = p.Memory
}).ToList();
我正在从两个表中获取值,但无法对它们进行分组或添加值。
您应该将 group by 添加到 LINQ 查询中并使用 Distinct().Count() 和 Sum() 聚合函数:
var query = from a in ghostEntities.DeviceList
join b in ghostEntities.DeviceMaster on a.DeviceMasterId equals b.Id
group b by b.Brand into g
select new { g.Key, count =g.Select(x => x.Brand).Distinct().Count(), sum = g.Sum(x => x.Qty) };
您可以在 https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b 找到很多 LINQ 示例,希望对您有所帮助。
按 table 分组后,您将无法在连接操作中访问另一个 table 的字段,可能的解决方法是:
var results = (from a in DeviceList
join b in DeviceMaster
on a.DeviceMasterId equals b.Id
group new { a, b } by new { b.Brand } into grp
select new
{
Brand = grp.Key.Brand,
BrandCount = grp.Count(),
DeviceCount = grp.Sum(x=> x.a.Qty.GetValueOrDefault())
}).ToList();
这是我的 sql 命令:
select
b.Brand,
count(b.Brand) as BrandCount,
SUM(a.Qty) as DeviceCount
from (
select * from DeviceList
) as a
join DeviceMaster as b
on a.DeviceMasterId = b.Id
group by b.Brand
这是我到目前为止尝试过的方法:
var v1 = (from p in ghostEntities.DeviceMasters
join c in ghostEntities.DeviceLists on p.Id equals c.DeviceMasterId
select new table_Model {
Id = c.Id,
qty = c.Qty.Value,
month = c.DMonth,
brand = p.Brand,
model = p.Model,
memory = p.Memory
}).ToList();
我正在从两个表中获取值,但无法对它们进行分组或添加值。
您应该将 group by 添加到 LINQ 查询中并使用 Distinct().Count() 和 Sum() 聚合函数:
var query = from a in ghostEntities.DeviceList
join b in ghostEntities.DeviceMaster on a.DeviceMasterId equals b.Id
group b by b.Brand into g
select new { g.Key, count =g.Select(x => x.Brand).Distinct().Count(), sum = g.Sum(x => x.Qty) };
您可以在 https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b 找到很多 LINQ 示例,希望对您有所帮助。
按 table 分组后,您将无法在连接操作中访问另一个 table 的字段,可能的解决方法是:
var results = (from a in DeviceList
join b in DeviceMaster
on a.DeviceMasterId equals b.Id
group new { a, b } by new { b.Brand } into grp
select new
{
Brand = grp.Key.Brand,
BrandCount = grp.Count(),
DeviceCount = grp.Sum(x=> x.a.Qty.GetValueOrDefault())
}).ToList();