using group by in linq to sql - c#

I have a problem in group by with link to sql
first I have this tables :
client : Id_client , nom , prenom , villeId
ville: id_ville , nom
Code:
justiceDataContext dbContext = new justiceDataContext();
GridView1.DataSource = from client in dbContext.Client
join ville in dbContext.Commande
on client.villeId equals ville.Id_ville
group client by ville.nom into g
select new { City = g.Key, NumberOfClients = g.Count() };
GridView1.DataBind();
My objective is to get number of client by city (ville)
thank you

dbContext.Client
.GroupBy(c => c.villeId)
.Select(g => new {
CityName = dbContext.Villes.Where(v => v.Id_ville == g.Key),
NumberOfClient = g.Count()
}).ToList();
Another approach:
var result = dbContext.Villes
.Join(dbContextClients, v => v.IdVille, c => c.IdVille, (v, c) => new { client = c, ville = v })
.GroupBy(j => j.ville.IdVille)
.Select(g => new {
VilleName = g.First().ville.Name,
NumberOfClients = g.Count()
}).ToList();

Related

How to Convert the existing T-SQL Code to C# Ling query

I have a T-SQL Query that show Sum(TotalAmount) Sum(Discount) Sum(PayableAmount) from Table1 named p1 and show the Sum(PaidAmount) from Table2 named p2,
the tables p1 and p2 do not have any relationship with Forenkay and the primary key,
so I was not able to use the .net core method syntax _context.Table1.include(a=>a.table2) to join 2 tables because there is no relationship between these 2 tables,
So I have written the below code as T-SQL query and got the exact result that I wanted, but now I want to write the same T-SQL query as a LING query and use it inside my C#.net Core Controller code as query syntax or method syntax,
Here is my T-SQL Code that show Sum(TotalAmount) Sum(Discount) Sum(PayableAmount) from Table1 named p1 and show the Sum(PaidAmount) from Table2 named p2,
SELECT p1.PatientId,
SUM(p1.TotalAmount) as TotalTreatmentAmount,
SUM(p1.Discount) As TotalTreatmentDiscount,
SUM(p1.Payable) as TotalTreatmentPayable,
SUM(p1.Balance) as TotalTreatmentBalancce,
p2.TotalTreatmentPaidAmount
FROM PatientPayments as p1
join (SELECT p2.PatientId, SUM(p2.PaidAmount) as TotalTreatmentPaidAmount
FROM PatientPaymentHistories p2
where p2.PaymentType != 'Refund'
group by p2.PatientId) as p2
ON p2.PatientId = p1.PatientId
group by p1.PatientId, p2.TotalTreatmentPaidAmount
Here is my C# Code but this code does not work its wrong only the SQL code is working fine
public IActionResult ExportPatientPaymentDataToExcel()
{
var PatientPayments =
from p1 in _context.PatientPayments
join p2 in _context.PatientPaymentHistories on p1.PatientId equals p2.PatientId
select new
{
p1.PatientId,
p1.TotalAmount,
p1.Discount,
p1.Payable,
p2.PaidAmount
};
DataTable PatientPaymentTable = new DataTable("PatientPayment");
PatientPaymentTable.Columns.AddRange(new DataColumn[5]
{
new DataColumn("Patient ID"),
new DataColumn("Total Amount"),
new DataColumn("Total Discount"),
new DataColumn("Total Payable"),
new DataColumn("Total Paid"),
});
foreach (var PatientPayment in PatientPayments)
{
PatientPaymentTable.Rows.Add(
PatientPayment.PatientId,
PatientPayment.TotalAmount,
PatientPayment.Discount,
PatientPayment.Payable,
PatientPayment.PaidAmount
);
}
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(PatientPaymentTable);
using (MemoryStream stream = new MemoryStream())
{
wb.SaveAs(stream);
return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", GetLocalDateTime().Date.ToShortDateString() + " " + "PatientPayment_Data.xlsx");
}
}
}
Please help me to change the above T-SQL Code to C# Ling query
This should work as expected:
var query = _context.PatientPayments.Join(_context.PatientPaymentHistories
.Where(x => x.Type != "Refund")
.GroupBy(x => x.PatientId)
.Select(x => new
{
PatientId = x.Key,
TotalTreatmentPaidAmount = x.Sum(y => y.PaidAmount)
}),
x => x.PatientId,
y => y.PatientId,
(x, y) => new
{
PatientId = x.PatientId,
TotalAmount = x.TotalAmount,
Discount = x.Discount,
Payable = x.Payable,
Balance = x.Balance,
TotalTreatmentPaidAmount = y.TotalTreatmentPaidAmount
})
.GroupBy(x => new { PatientId = x.PatientId,
TotalTreatmentPaidAmount = x.TotalTreatmentPaidAmount })
.Select(x => new
{
PatientId = x.Key.PatientId,
TotalTreatmentAmount = x.Sum(y => y.TotalAmount),
TotalTreatmentDiscount = x.Sum(y => y.Discount),
TotalTreatmentPayable = x.Sum(y => y.Payable),
TotalTreatmentBalancce = x.Sum(y => y.Balance),
TotalTreatmentPaidAmount = x.Key.TotalTreatmentPaidAmount
});
Based on your T-SQL, try it like this
var query = _context.PatientPayments
.Join(_context.PatientPaymentHistories
.Where(s => s.PaymentType != 'Refund')
.GroupBy(p => p.PatientId)
.Select(g => select new {
PatientId = g.Key,
TotalTreatmentPaidAmount = g.Sum(x => x.PaidAmount)
}),
p1 => p1.PatientId,
p2 => p2.PatientId,
(p1, p2) => new { PatientPayments = p1, PatientPaymentHistories = p2 })
.GroupBy(s => new { s.PatientPayments.PatientId, s.PatientsPaymentHistories.TotalTreatmentPaidAmount })
.Select(gs => new
{
gs.Key.PatientId,
TotalTreatmentAmount = gs.Sum(x => x.PatientPayments.TotalAmount),
TotalTreatmentDiscount = gs.Sum(x => x.PatientPayments.Discount),
TotalTreatmentPayable = gs.Sum(x => x.PatientPayments.Payable),
TotalTreatmentBalancce = gs.Sum(x => x.PatientPayments.Balance),
gs.Key.TotalTreatmentPaidAmount
};

Group By Query with Entity Framework Query Method

i have this query and i wanna to change to linq query methods:
select o.OrderID,o.OrderNo, o.OrderDate, SUM(TotalAmount) Total
from orders o inner join
OrderDetails e on o.OrderID=e.OrderID
group by o.OrderNo, o.OrderDate,o.OrderID order by o.OrderNo desc
i have been trying the follow:
public List<Orders>List()
{
var list = new List<Orders>();
try
{
using (var db = new MyDatabaseEntities())
{
list = db.Orders.Select(o => new { o.OrderID, o.OrderNo, o.OrderDate, o.OrderDetails.TotalAmount}).
GroupBy(x => new { x.OrderID, x.OrderNo, x.OrderDate }).
Select(o => new
{
o.Key,
id = o.OrderID,
order = o.NumOrder,
date = o.OrderDate,
Total = o.Sum(o.TotalAmount)
}).Tolist();
}
}
catch(Exception e)
{
throw new Exception(e.Message);
}
return list;
}
Someone can Help me?
I think try this:
var list=db.Orders.Join(OrderDetails,
o=>o.OrderID
e=>e.OrderID
(o,e)=>new{Orders=o,OrderDetails=e})
.GroupBy(o=>new {o.OrderNo, o.OrderDate,o.OrderID})
.OrderBy(x=>x.Key.OrderNo)
.Select(o=>new{
o.Key.OrderID,
o.Key.OrderNo,
o.Key.OrderDate,
Total=o.SUM(x=>x.TotalAmount)})
.ToList();
Try this :
Sql like syntax
from t in TblOrders
join d in TblOrderDetails
on t.Id equals d.OrderId
group d by new {t.Id, t.OrderNo, t.OrderDate} into g
orderby g.Key.OrderNo descending
select new
{
ID = g.Key.Id,
OrderNo = g.Key.OrderNo,
OrderDate = g.Key.OrderDate,
amount = g.Sum(x=>x.Rate)
}
lambda like:
TblOrders
.Join (
TblOrderDetails,
t => t.Id,
d => d.OrderId,
(t, d) =>
new
{
t = t,
d = d
}
)
.GroupBy (
temp0 =>
new
{
Id = temp0.t.Id,
OrderNo = temp0.t.OrderNo,
OrderDate = temp0.t.OrderDate
},
temp0 => temp0.d
)
.OrderByDescending (g => g.Key.OrderNo)
.Select (
g =>
new
{
ID = g.Key.Id,
OrderNo = g.Key.OrderNo,
OrderDate = g.Key.OrderDate,
amount = g.Sum (x => x.Rate)
}
)

Join and Group By using Lambda Expression

Query
var grpby4 = from u in dtEmp.AsEnumerable()
join v in dtDept.AsEnumerable() on u.Field<int>("DepartmentID") equals v.Field<int>("DepartmentID")
group u by v.Field<string>("DeptName") into g
select new { DeptName = g.Key, Records = g };
How write the same Query using Lambda Expression?
Using this handy webpage I get
dtEmp.AsEnumerable()
.Join(dtDept.AsEnumerable(),
u => u.Field<int>("DepartmentID"),
v => v.Field<int>("DepartmentID"),
(u, v) => new { u, v })
.GroupBy(τ0 => τ0.v.Field<string>("DeptName"), τ0 => τ0.u)
.Select(g => new { DeptName = g.Key, Records = g })

How to write lambda expression for an sql expression?

I have an SQL expression
select S.SpecialtyName, COUNT(distinct SUC.SiteUserId) as Subscribers
from SiteUserContent SUC Inner join
Specialties S on SUC.SpecialtyId = S.SpecialtyId Inner join
SiteUser SU on SUC.SiteUserId = SU.SiteUserId
where SU.DeletedFlag = 0
group by S.SpecialtyName
Order by S.SpecialtyName
What will be the corresponding LINQ expression for the same?
from suc in context.SiteUserContent
join s in context.Specialties on suc.SpecialtyId equals s.SpecialtyId
join su in context.SiteUser on suc.SiteUserId equals su.SiteUserId
where su.DeletedFlag == 0
select new { suc.SiteUserId, s.SpecialityName } into x
group x by x.SpecialityName into g
orderby g.Key
select new {
SpecialityName = g.Key,
Subscribers = g.Select(i => i.SiteUserId).Distinct().Count()
}
Generated SQL will not be same, but I think result of query execution should be same.
var results = contex.SiteUserContent
.Join(context.Specialties, suc => suc.SpecialtyId, s => s.SpecialtyId, (suc, s) => new { suc, s })
.Join(context.SiteUser, i = i.suc.SiteUserId, su => su.SiteUserId, (i, su) => new { suc = i.suc, s = i.s, su = su })
.Where(i => i.su.DeletedFlag == 0)
.GroupBy(i => i.s.SpecialtyName)
.Select(g => new {
SpecialityName = g.Key,
Subscribers = g.Select(i => i.suc.SiteUserId)
.Distinct()
.Count()
})
.OrderBy(i => i.SpecialityName);

how convert sql to linq

How do I do this
Select top 10 Foo from MyTable
SELECT TOP (30) Item, Descripcion, SUM(Amount) AS Suma
FROM Venat
GROUP BY Item, Descripcion
ORDER BY Suma
in Linq to SQL?
with this only agrup by Item but not Description
var filtroprimeros30 = from nuevo in registrosVipDosAños
group nuevo by nuevo.Item into g
select new
{
Item = g.Key,
Suma = g.Sum(nuevo => nuevo.Amount)
};
Use anonymous type for grouping:
var filtroprimeros30 =
(from nuevo in registrosVipDosAños
group nuevo by new { nuevo.Item, nuevo.Description } into g // here
select new {
g.Key.Item,
g.Key.Description,
Suma = g.Sum(n => n.Amount)
})
.OrderBy(x => x.Suma)
.Take(30);
I'd actually go this way (because query syntax has nice syntax for grouping, but do not have ability to take N items):
var items = from n in registrosVipDosAños
group n by new { n.Item, n.Description } into g
select new {
g.Key.Item,
g.Key.Description,
Suma = g.Sum(x => x.Amount)
};
var topItems = items.OrderBy(x => x.Suma).Take(30);
Query still will be executed only once, but now it's more readable.
syntax alternative
var filtroprimeros30 = registrosVipDosAnos
.GroupBy(m => new {m.Item, m.Description})
.Select(g => new {
Item = g.Key.Item,
Description = g.Key.Description,
Suma = g.Sum(n => n.Amount)
})
.OrderBy(x => x.Suma)
.Take(30);

Categories