简体   繁体   中英

I need to convert sql to Linq

This is my sql command:

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 

Here is what I've tried so far:

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();

I am getting the values form two tables but can't group them or add the values.

You should add group by into your LINQ query and use Distinct().Count() and Sum() aggregation functions:

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) };

You can find a lot of LINQ samples at https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b , I hope it will help you.

Once you group by a table, you lose access to the fields of the other table in the join operation, a possible workaround would be:

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();

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM