Linq Group by id - c#

var query = from c in context.Auto
join r in context.Label on c.idAutoChar equals r.idAutoChar
join g in context.Rent on c.idAuto equals g.idAuto
where c.idAutoChar == r.idAutoChar && c.idAuto == g.idAuto
group new {c, r, g} by new {c.idAuto, r.Name, c.RegNumber, g.Summ} into v
select new
{
v.Key.idAuto,
v.Key.Name,
v.Key.RegNumber,
Sum = (from b in v select v.Key.Summ).Sum()
};
I need to group Cars by idAuto with a column of SUM(Summ) but it didn't work correctly. Could you please help.

var query = from c in context.Auto
join r in context.Label on c.idAutoChar equals r.idAutoChar
join g in context.Rent on c.idAuto equals g.idAuto
//where c.idAutoChar == r.idAutoChar && c.idAuto == g.idAuto //???
group new {c, r, g} by new {c.idAuto, r.Name, c.RegNumber} into v
select new
{
v.Key.idAuto,
v.Key.Name,
v.Key.RegNumber,
Sum = v.Sum(item => item.Key.Summ)
};
use Sum = v.Sum(item => item.Key.Summ) and don't group by Summ, otherwise it will produce a group item for each different Summ value.
BTW, why do you need your where condition - it replicates on conditions of your joins

Assuming that g.Summ is a numeric value you want to sum on, and not something you actually want to group on then it shouldn't be part of the key.
I've no way of testing this, but something like this might be the answer:
c in context.Auto
join r in context.Label on c.idAutoChar equals r.idAutoChar
join g in context.Rent on c.idAuto equals g.idAuto
where c.idAutoChar == r.idAutoChar && c.idAuto == g.idAuto
group new {c, r, g} by new {c.idAuto, r.Name, c.RegNumber} into v
select new
{
v.Key.idAuto,
v.Key.Name,
v.Key.RegNumber,
Sum = (from b in v
select b.Summ).Sum()
};
Note we don't include c.Summ in the group by, and the Sum is then over b.Summ. I also think that g (Rent?) isn't actually required in this linq statement.

Related

Selecting max in linq query or rewriting to method chain syntax

I managed to turn this SQL query:
SELECT c.carId, c.Codename, count(c.CarId) as [CarCount],
FROM [DbEfTesting].[dbo].[Cars] c
left join Accessories a on c.CarId = a.CarId
left join CarsPeople cp on cp.CarId = c.CarId
left join People p on cp.PersonId = p.PersonId
group by c.CarId, c.Codename
into a LINQ query:
var x = from c in _context.Cars
join a in _context.Accessories on c.CarId equals a.Car.CarId
join j in _context.CarsPeople on c.CarId equals j.CarId
join p in _context.People on j.PersonId equals p.PersonId
group c by new { c.CarId, c.Codename } into g
select new VMCarAggregate()
{
CarId = g.Key.CarId,
Codename = g.Key.Codename,
CarCount = g.Count()
};
But now I'm lost trying to include a max value e.g the SQL:
SELECT c.carId, c.Codename, count(c.CarId) as [CarCount], max(a.AccessoryId) ...
I googled it and found lots of answers for method syntax. If I were using method chain syntax, I know I could do something like this:
_context.Accessories.Max(a => a.AccessoryId);
but I can't figure out how to do the group by in method chain syntax so either:
How can I convert that query to method syntax?
or
How can I inject a select on the max a.AccessoryId in the LINQ query format?
Try the below code once:
var x = from c in _context.Cars
join a in _context.Accessories equals a.Car.CarId
join j in _context.CarsPeople on c.CarId equals j.CarId
join p in _context.People on j.PersonId equals p.PersonId
group new { c.CarId, c.Codename, a.AccesoryId } by new { c.CarId, c.Codename } into g
select new
{
CarId = g.Key.CarId,
Codename = g.Key.Codename,
CarCount = g.Count(),
MaxAccesory = g.Max(z => z.AccesoryId)
};

how do i handle value when the value is null or Empty using linq query

i have this code that returns all tickets with reply info so when there is no status value in Ticket_Reply entered i need to show "XXX"
enter var query = (from st in Db.Support_Teckets
join pr in Db.Technical_problem on st.Technical_problem_Id equals pr.Technical_problem_Id
join x in
from rp in Db.Ticket_Reply.GroupBy(m =>
m.Support_Tecket_Id).Select(m => m.OrderByDescending(x=>x.Date).FirstOrDefault())
join tr in Db.trainers on rp.trainer_id equals tr.trainer_id
select new {rp,tr}
on st.Support_Tecket_Id equals x.rp.Support_Tecket_Id into g
from gx in g.DefaultIfEmpty()
select new SupportTicketsDetails
{
Status = gx.rp.Status,
}).ToList().OrderByDescending(a => a.Created_Date);
thanks for your cooperation
Assuming gx.rp.Status is a string Try using the ternary conditional operator e.g.
Status = string.IsNullOrWhiteSpace(gx.rp.Status) ? "XXX":gx.rp.Status
i.e
enter var query = (from st in Db.Support_Teckets
join pr in Db.Technical_problem on st.Technical_problem_Id equals pr.Technical_problem_Id
join x in
from rp in Db.Ticket_Reply.GroupBy(m =>
m.Support_Tecket_Id).Select(m => m.OrderByDescending(x=>x.Date).FirstOrDefault())
join tr in Db.trainers on rp.trainer_id equals tr.trainer_id
select new {rp,tr}
on st.Support_Tecket_Id equals x.rp.Support_Tecket_Id into g
from gx in g.DefaultIfEmpty()
select new SupportTicketsDetails
{
Status = string.IsNullOrWhiteSpace(gx.rp.Status) ? "XXX":gx.rp.Status,
}).ToList().OrderByDescending(a => a.Created_Date);

group join with left join group return null

I have a group join with 2 joins group, one of the group joins can be null, in my query C is the group that I join with a left join this query give me and null exception
from A in contexto.A.Where(i => i.EmpresaId == id)
join B in contexto.B
on A.Id equals B.AId
join D in contexto.D
on B.BId equals D.Id
join C in contexto.C
on A.Id equals C.AId
into c
from C in c.DefaultIfEmpty()
group new { A, C, D} by A into grupo
select new ADTO{
Clave = grupo.Key.Clave,
Nombre = grupo.Key.Nombre,
Lista1 = grupo.Select(t =>
t.D.Nombre
).ToList(),
Valores1 = grupo.Select(t => new ValorDTO
{
a= t.C.A,
b= t.C.B,
c= t.C.c
}
).DefaultIfEmpty(new ValorBMDTO()).ToList()
}).ToList();

Add additional fields to Linq group by

I have the LINQ to SQL as below, which works fine.
var qry = (from h in dc.Timesheets
join s in dc.Users on h.UserID equals s.UserID
join ug in dc.UserGroups on s.UserGroupID equals ug.UserGroupID
where h.BookedOn >= _dateFrom.Value && h.BookedOn <= _dateTo.Value
group h by ug.UserGroupID into g
orderby g.Count() descending
select new
{
UserGroupingID = g.Key,
BookingsPerDay = g.Count() / days
}).ToList();
Now I want to add the name of the User Group, but somehow I struggle to get the LINQ right.
My limited knowledge tells me I should add the Description to the Group clause as follow, but it's a no-go:
I try:
var qry = (from h in dc.Timesheets
join s in dc.Users on h.UserID equals s.UserID
join ug in dc.UserGroups on s.UserGroupID equals ug.UserGroupID
where h.BookedOn >= _dateFrom.Value && h.BookedOn <= _dateTo.Value
group h, GroupDescription = ug.Description by ug.UserGroupID into g
orderby g.Count() descending
select new
{
UserGroupingID = g.Key,
Description = g.Key.GroupDescription
BookingsPerDay = g.Count() / days
}).ToList();
Error: Cannot convert lambda expression to type
'System.Collections.Generic.IEqualityComparer' because it is not
a delegate type
I think you might missing the new keyword here!!
var qry = (from h in dc.Timesheets
join s in dc.Users on h.UserID equals s.UserID
join ug in dc.UserGroups on s.UserGroupID equals ug.UserGroupID
where h.BookedOn >= _dateFrom.Value && h.BookedOn <= _dateTo.Value
group new {h, GroupDescription = ug.Description} by new {GroupDescription} into g
orderby g.Count() descending
select new
{
UserGroupingID = g.Key,
Description = g.Key.GroupDescription
BookingsPerDay = g.Count() / days
}).ToList();
Shouldn't it be an == for the GroupDescription? And aren't you missing a comma in the select new statement?

How to Use Data Inside Var in Linq?

I want to sum records using Group by from the all data inside "result view".
can anyone guide me for this.!
Here is My Code
var tData1 = (from i in _data.Transactions
join y in _data.DeviceInformations on i.DeviceInfoId equals y.DeviceInfoId
join u in _data.AccountDevices on y.DeviceInfoId equals u.DeviceInfoId
where y.Active == true && u.AccountId == 1000001 && u.Active == true
group i by i.DeviceInfoId into g
select g.OrderByDescending(t => t.DateCreated)).ToList();
foreach (var xCo in tData1)
{
//I am getting Data in xCo
}
Based on #Nayeem Mansoori solution you can try this.
var tData1 = (from i in _data.Transactions
join y in _data.DeviceInformations on i.DeviceInfoId equals y.DeviceInfoId
join u in _data.AccountDevices on y.DeviceInfoId equals u.DeviceInfoId
where y.Active == true && u.AccountId == 1000001 && u.Active == true
group i by i.DeviceInfoId into g
select new {Id = DeviceInfoId, sum = g.Sum(x=>x.DeviceInfoId)};

Categories

Resources