WHERE condition with SELECT, MAX statement using LINQ/Lambda - c#

I am trying to convert below SQL query to LINQ/Lambda in C#
SELECT DISTINCT M.InternalID, P.Code
FROM (
dbo.MeasureValue MV
INNER JOIN dbo.Measure M ON MV.MeasureID = M.ID
INNER JOIN dbo.Provider P ON MV.ProviderID = P.ID
)
WHERE MV.ReportingDate = (
SELECT MAX(ReportingDate)
FROM (
SELECT ReportingDate
FROM dbo.MeasureValue
WHERE MeasureID = MV.MeasureID
) MaxReportingDate
);
I have got so far,
(from MV in MeasureValues
join M in Measures on MV.MeasureID equals M.ID
join P in Providers on MV.ProviderID equals P.ID
Where //???
select new //Distinct??
{ M.InternalID, P.Code} )
Could someone please guide me how to use nested WHERE condition as in SQL query and do MAX of nested SELECT and DISTINCT on whole?
As a whole the LINQ/Lamda should output same result as SQL query.
*I am new to SQL and LINQ
Thanks in advance.

Try this one:
var query =
from mv in MeasureValues
join m in Measures on mv.MeasureID equals m.ID
join p in Providers on mv.ProviderID equals p.ID
where mv.ReportingDate ==
(from mv2 in MeasureValues
where mv2.MeasureID == mv.MeasureID
orderby mv2.ReportingDate descending
select mv2.ReportingDate
).FirstOrDefault()
select new { m.InternalID, p.Code };
var distinct =
from q in query
group q by new { q.InternalID, q.Code} into gr
select new
{
InternalID = gr.First().InternalID,
Code = gr.First().Code
};
var result = distinct.ToList();
Another option to find max ReportingDate:
var query =
from mv in MeasureValues
join m in Measures on mv.MeasureID equals m.ID
join p in Providers on mv.ProviderID equals p.ID
where mv.ReportingDate == MeasureValues.Where(x => x.MeasureID == mv.MeasureID).Select(x => x.ReportingDate).Max()
select new { m.InternalID, p.Code };

Related

Join Table Group By Summary On Linq

Hi I try to convert the SQL query to LINQ.
SELECT C.ID, SUM(S.AMOUNT*CS.PRICE) AS TOTALCATEGORYSUMMARY
FROM CATEGORY C
INNER JOIN PRODUCT P ON P.CATEGORYID=C.ID
INNER JOIN PSTOCK S ON S.PRODUCTID=P.ID
INNER JOIN PCOST CS ON CS.PRODUCTID=P.ID
GROUP BY C.ID
I try as below:
var qry = from c in categories
join p in products on c.Id equals p.CategoryId
join s in stoks on p.Id equals s.ProductId
join t in costs on p.Id equals t.ProductId
group new {c} by new { c.Name,s.Stock,t.Amount } into ct
select (new { ct.Key.Name, AllCost=ct.Key.Amount * ct.Key.Stock });
How can I do this?
From your SQL query, your LINQ statement should be:
var qry = from c in categories
join p in products on c.Id equals p.CategoryId
join s in stoks on p.Id equals s.ProductId
join t in costs on p.Id equals t.ProductId
group new { c.Id, s.Amount, t.Price } by c.Id into ct
select new { Id = ct.Key.Id, AllCost = ct.Sum(x => x.Amount * x.Price) };
References
Group by single property
Enumerable.Sum method

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

Joining 2 separate LINQ queries in C# with objectFactory

I'm trying to achieve the following SQL query which works the way I need it to into LINQ. I have 2 separate SQL queries which I join and than select the product if the groups price is greater than an individual price. I'm using LINQ to objects and have an Object Factory for the Purchases and Products table.
select DISTINCT(a.Name) from
(select p.Prod_ID, p.Name, SUM(p.Price) as Total
from Tb_AvailableProduct p, Tb_Purchases o
where p.Prod_ID = o.Prod_ID
group by p.Prod_ID, p.Name) a
JOIN
(select p.Prod_ID, p.Price
from Tb_AvailableProduct p, Tb_Purchases o
where p.Prod_ID = o.Prod_ID) b
on a.Prod_ID = b.Prod_ID
where a.Total > b.Price
I have this first query in Linq, but I only want to select a Product Name if that product's group price is greater than the product's individual price.. i.e more than one product has been sold. I'm trying to accomplish this with a sum and not using a count.
from o in this.myObjectFactory.ThePurchases
join p in this.myObjectFactory.TheProducts.Values
on o.ProductID equals p.ProductID
where o.CustomerID == customer.CustomerID
group p by p.ProductID into query1
select new { ProductID = query1.Key, TotalPurchasesThisYear = query1.Sum (p => p.Price)});
Something like this should probably work (it's very similar to your SQL query):
var result =
from a in
(
from p in TheProducts
join o in ThePurchases
on p.ProductID equals o.ProductID
group p by new { p.ProductID, p.Name, p.Price } into g
select new
{
ProductID = g.Key.ProductID,
Name = g.Key.Name,
Total = g.Sum(i => i.Price)
}
)
join b in
(
from p in TheProducts
join o in ThePurchases
on p.ProductID equals o.ProductID
select new
{
ProductID = p.ProductID,
Price = p.Price
}
)
on a.ProductID equals b.ProductID
where a.Total > b.Price
select a.Name;
result = result.Distinct();

LINQ OrderBy Count of Records in a Joined Table

I'm having trouble translating the following tSQL to LINQ to SQL in C#. Any help would be much appreciated:
SELECT P.Name
FROM Product P
INNER JOIN OrderItems OI ON P.productID = OI.productID
INNER JOIN Orders O ON OI.orderID = O.orderId
WHERE P.Active = 1 AND O.Status > 2
ORDER BY count(OI.orderID) DESC
It's the ordering by the COUNT of a JOINED table that's throwing me for a loop.
Here's what I have so far (with no orderby):
from p in CRM.tProducts
join oi in CRM.tOrderItems on p.prodID equals oi.prodID
join o in CRM.tOrders on oi.orderID equals o.orderID
where o.status > 1 && p.active == true
select p;
Thanks for any help!
You need to execute a group by if you want the count
SELECT P.Name
FROM Product P
INNER JOIN OrderItems OI ON P.productID = OI.productID
INNER JOIN Orders O ON OI.orderID = O.orderId
WHERE P.Active = 1 AND O.Status > 2
GROUP BY P.Name
ORDER BY count(*) DESC
I'll assume you actually want the count for each group in the projection.
from p in CRM.tProducts
join oi in CRM.tOrderItems on p.prodID equals oi.prodID
join o in CRM.tOrders on oi.orderID equals o.orderID
where o.status > 1 && p.active == true
group p by p.Name into nameGroup
orderby nameGroup.Count()
select new { Name = nameGroup.Key, Count = nameGroup.Count() };
See comment to question.
How to do "order by" in linq ->
If you have
var alist = .... select new { prd = p, ord = o };
you can do
alist.sort( (a, b) => a.ord.CompareTo(b.ord) );
to sort it in place.

Linq Sub-Select

How do I write a sub-select in LINQ.
If I have a list of customers and a list of orders I want all the customers that have no orders.
This is my pseudo code attempt:
var res = from c in customers
where c.CustomerID ! in (from o in orders select o.CustomerID)
select c
How about:
var res = from c in customers
where !orders.Select(o => o.CustomerID).Contains(c.CustomerID)
select c;
Another option is to use:
var res = from c in customers
join o in orders
on c.CustomerID equals o.customerID
into customerOrders
where customerOrders.Count() == 0
select c;
Are you using LINQ to SQL or something else, btw? Different flavours may have different "best" ways of doing it
If this is database-backed, try using navigation properties (if you have them defined):
var res = from c in customers
where !c.Orders.Any()
select c;
On Northwind, this generates the TSQL:
SELECT /* columns snipped */
FROM [dbo].[Customers] AS [t0]
WHERE NOT (EXISTS(
SELECT NULL AS [EMPTY]
FROM [dbo].[Orders] AS [t1]
WHERE [t1].[CustomerID] = [t0].[CustomerID]
))
Which does the job quite well.
var result = (from planinfo in db.mst_pointplan_info
join entityType in db.mst_entity_type
on planinfo.entityId equals entityType.id
where planinfo.entityId == entityId
&& planinfo.is_deleted != true
&& planinfo.system_id == systemId
&& entityType.enity_enum_id == entityId
group planinfo by planinfo.package_id into gplan
select new PackagePointRangeConfigurationResult
{
Result = (from planinfo in gplan
select new PackagePointRangeResult
{
PackageId = planinfo.package_id,
PointPlanInfo = (from pointPlanInfo in gplan
select new PointPlanInfo
{
StartRange = planinfo.start_range,
EndRange = planinfo.end_range,
IsDiscountAndChargeInPer = planinfo.is_discount_and_charge_in_per,
Discount = planinfo.discount,
ServiceCharge = planinfo.servicecharge,
AtonMerchantShare = planinfo.aton_merchant_share,
CommunityShare = planinfo.community_share
}).ToList()
}).ToList()
}).FirstOrDefault();
var res = (from c in orders where c.CustomerID == null
select c.Customers).ToList();
or Make Except()

Categories

Resources