Add Max and Average in linq query - c#

I've got an sql query below:
SELECT MAX(r.Suburb), AVG(s.Longitude) AS Longitude, AVG(s.Latitude) AS Latitude
From CafeAddress r inner join Cafe s on s.CafeId = r.CafeId
WHERE r.Region = 'Sydney'
which outputs:
Bankstown 174.759541622222 -36.8552809611111
The query should be getting all suburbs in the region e.g. Sydney is the region and suburbs would include Bankstown etc..
How would I add max and average in my linq query below? (region id is a user input (string))
var region = from cafeAddress in _context.CafeAddress
join cafe in _context.Cafe on cafeAddress.CafeId equals cafe.CafeId
where cafeAddress.StateProvinceRegion == regionId
select new { StateProvinceRegion = cafeAddress.Suburb.Max(), cafe.Latitude, cafe.Longitude };
I'm only able to do it through using a group by but I'm trying to avoid that.

I think this would be getting fairly close:
var query =
from cafeAddress in _context.CafeAddress
join cafe in _context.Cafe on cafeAddress.CafeId equals cafe.CafeId
where cafeAddress.StateProvinceRegion == regionId
orderby cafeAddress.Suburb descending
group new
{
cafeAddress.Suburb,
cafe.Latitude,
cafe.Longitude
} by cafeAddress.StateProvinceRegion into g
select new
{
StateProvinceRegion = g.First().Suburb,
Latitude = g.Average(x => x.Latitude),
Longitude = g.Average(x => x.Longitude),
};
Or this slight variant:
var query =
from cafeAddress in _context.CafeAddress
join cafe in _context.Cafe on cafeAddress.CafeId equals cafe.CafeId
where cafeAddress.StateProvinceRegion == regionId
orderby cafeAddress.Suburb descending
group new
{
cafeAddress.Suburb,
cafe.Latitude,
cafe.Longitude
} by cafeAddress.StateProvinceRegion into gs
from g in gs.Take(1)
select new
{
StateProvinceRegion = g.Suburb,
Latitude = gs.Average(x => x.Latitude),
Longitude = gs.Average(x => x.Longitude),
};

Related

LINQ Join and Sum Query returns duplicate Results

I am running this query in LINQ which joins tables and returns the sum of sales per District ID.
var resultsalescity = (from so in _companysales
join en in _entity
on so.Id equals en.Id
group so by so.Id into totaledorders
from tot in totaledorders
join ad in _address
on tot.Id equals ad.EntityId
select new Salescities {
Totaledvalue = totaledorders.Sum(s = >s.TotalCost),
District = ad.DistrictId.ToString(),
}).ToList();
return resultsalescity;
I get duplicates values returns:
[{"totaledvalue":3855.00,"district":"568"},{"totaledvalue":3855.00,"district":"568"}}
.....
How can I drop the duplicates on the district ID to return only one value for each district?
I'm getting 4 duplicates District ID in results with different sales values
It's correct. Because It's grouped by Id. The actual result of 4 duplicates District ID would be different _companysales.Id. So you might be looking for something like this
var groupedByIdAndDistrictData = (from so in _companysalesRepo.QueryNoTracking
join en in _entityRepo.QueryNoTracking on so.PharmacyId equals en.Id
join ad in _addressRepo.QueryNoTracking on so.PharmacyId equals ad.EntityId
group so by new {
so.Id,
ad.DistrictId
}
into totaledeorders
select new Salescities {
Totaledvalue = totaledeorders.Sum(s = >s.TotalCost),
District = totaledeorders.Key.DistrictId.ToString()
}).ToList();
var resultsalescity = groupedByIdAndDistrictData.GroupBy(p = >p.District)
.Select(g = >new Salescities {
Totaledvalue = g.Sum(s = >s.Totaledvalue),
District = g.Key
}).ToList();
return resultsalescity;

Sum Columns from joined tables to get a calculated value using Linq to SQL

In the above diagram for each customer I want to select all orders and then for each order I have calculate a TotalPrice = (Sum of all Food Items included in order * Quantity) + ExtraPrice. I am struggling to create a query for it using linq to sql.
var res = (from a in dc.orders
join b in dc.orderLines on a.orderId equals b.fk_orderId
join c in dc.foodItems on b.fk_foodId equals c.foodId
where a.fk_custId == cID
group new { a,c,b } by a into g
select new
{
OID1 = g.Key.orderId,
date1 = g.Key.date.Value.Date,
price1 = g.Sum(x => x.c.price * x.b.quantity) + g.Key.orderLines.Select(o => o.extraPrice).Sum()
});
Given above is linq query I was looking for.
Should be something close to this. I'm not around a computer to test so let me know if you get errors.
db.orders.Select(o => new { o.orderid, o.date, TotalPrice = ( (o.orderLines.Select(ol => ol.food items.Count()).Sum() * o.Quantity) + o.extraPrice) } )

Join two linq queries on one key column to get one result set

Here I want to join the out put of the first query(one column) to the result of the 2nd query to get a one result set. How can I merge them.(CONCAT doesn't work as required. eg: var query2 = query.concat(query1);)
var query = (from PP in _db.paymentPlans
join APP in _db.Applications on PP.applicationID equals APP.ApplicationId
join C in _db.Courses on APP.courseID equals C.courseID
where PP.active == true && APP.agentID == agentID
orderby C.courseID ascending
group new {C,PP} by new {C.courseID} into totalRecievable
select new PdPpAppCourseModel
{
courseID = totalRecievable.Key.courseID,
totalAmount = totalRecievable.Sum(x => x.PP.totalAmount)
}).ToList();
var query1=(from PD in _db.paymentDetails
join PP in _db.paymentPlans on PD.paymentPlanID equals PP.paymentPlanID
join APP in _db.Applications on PP.applicationID equals APP.ApplicationId
join C in _db.Courses on APP.courseID equals C.courseID
where PP.active == true && APP.agentID == agentID
orderby C.courseID ascending
group new { C,PD } by new { C.courseID, C.cricosCode, C.courseName } into paymentsCourseWise
select new PdPpAppCourseModel
{
courseID = paymentsCourseWise.Key.courseID,
cricosCode = paymentsCourseWise.Key.cricosCode,
courseName = paymentsCourseWise.Key.courseName,
paidAmount = paymentsCourseWise.Sum(x => x.PD.paidAmount)
}).ToList();
You could join query1 and query like this
var result = (from q1 in query1
join q in query on q1.courseID = q.courseID
select new PdPpAppCourseModel
{
courseID = q1.Key.courseID,
cricosCode = q1.Key.cricosCode,
courseName = q1.Key.courseName,
paidAmount = q1.Sum(x => x.PD.paidAmount),
totalAmount = q.totalAmount
}).ToList();

Linq Dynamic Query With Group By

I need extra where clause for my Linq query. For example if customer choose a date filter so i need to date filter to my query etc... When i try to myQuery.Where predicate there is visible just group by's field.
How can i append new where condition to my query.
//for example i need dynamically append o.OrderDate==Datetime.Now or another where clause
var myQuery =(from o in _db.Orders
join l in _db.OrderLines.Where(x => x.ParaBirimi == model.ParaBirimi) on o.orderId equals
l.OrderId
where o.OrderDate.Value.Year == year1
group o by new {o.OrderDate.Value.Month}
into g
select
new
{
Month = g.Key.Month,
Total = g.Select(t => t.OrderLines.Sum(s => s.OrderTotal)).FirstOrDefault()
});
You are too late at the end of the query to add new Where. You have already grouped the data, and projected it, removing nearly all the fields.
Try:
var baseQuery = from o in _db.Orders
join l in _db.OrderLines.Where(x => x.ParaBirimi == model.ParaBirimi) on o.orderId equals l.OrderId
where o.OrderDate.Value.Year == year1
select new { Order = o, OrderLine = l };
if (something)
{
baseQuery = baseQuery.Where(x => x.Order.Foo == "Bar");
}
var myQuery = (from o in baseQuery
group o by new { o.Order.OrderDate.Value.Month }
into g
select
new
{
Month = g.Key.Month,
Total = g.Sum(t => t.OrderLine.OrderTotal)
});
Clearly you can have multiple if. Each .Where() is in && (AND) with the other conditions.
Note how the result of the join is projected in an anonymous class that has two properties: Order and OrderLine

transform sql to linq with join, group-by and where

I have the following sql, which I want to convert to linq
SELECT Contrato.finca, SUM(Pago.Importe_subtotal)
FROM Pago, Contrato
WHERE Pago.Contrato = Contrato.ID AND Pago.pagado = 1
GROUP BY Contrato.finca
ORDER BY 2 DESC
GO
What I have now in linq is the following, but the group by doesn't work.
var x = from contrato in ctx.Contratos
join pago in ctx.Pagos
on contrato.ID equals pago.Contrato
where pago.pagado == true
group contrato by contrato.finca
select contrato.Finca1;
Think this should work:
ctx.Pagos.Where(m=>m.pagado==true).GroupBy(m=>m.Contrato.finca)
.Select(m=> new { Id= m.Key, Val= m.Sum(n => n.Importe_subtotal)})
Try
var x = from contrato in ctx.Contratos
join pago in ctx.Pagos
on contrato.ID equals pago.Contrato
where pago.pagado == true
group new {contrato, pago} by contrato.finca into g
select new {
key = g.Key,
sum = g.Sum(p => p.pago.Importe_subtotal)
};

Categories