LINQ OrderBy Count of Records in a Joined Table - c#

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.

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

Left Join only return values where UserID match

Left join return duplicate products when 1 or more user save same product.
I solved the problem in SQL query.here's a query:
select p.ProductID,
(case when c.UserID = 3 then 'true' else 'false' end) as flag
from product as p
left join SavedItem as c on product.ProductID = c.ProductID and
c.UserID = 3
can't figure out how to do in a Entity framework.
left join SavedItem as c on product.ProductID = c.ProductID and
c.UserID = 3
Left join can be solve like this:
join c in SavedItem on p.ProductID equals c.ProductID into lj
from c in lj.DefaultIfEmpty()
c.UserID = 3 where to place this?
Try this:
var query= from product in context.Products
from SavedItem in context.SavedItems.Where(c=> c.ProductID = product.ProductID && c.UserID == 3).DefaultIfEmpty()
select new {
ProductID=product.ProductID,
Flag=(SavedItem==null || SavedItem.UserID != 3) ? false : true
};
Here! I found the solution.
from product in context.Products
join c in context.SavedItems
on new { p1 = (int?)product.ProductID , p2 = (int?)cat.UserID }
equals new { p1 = c.ProductID ,p2 = c.UserID} into lj
from c in lj.DefaultIfEmpty()
select new{
...
flag = (c.UserID == cat.UserID ? "true" : "false"),
...
}

WHERE condition with SELECT, MAX statement using LINQ/Lambda

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

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

How to join and select table data in mvc C#?

In my project I have services.
So in side the service I want to join tables and want to select more than one table data.
So I write this cording.
var query1 = from opv in _opvRepository.Table
join o in _orderRepository.Table on opv.OrderId equals o.Id
join g in _graduandRepository.Table on opv.graduand_id equals g.graduand_id
join pv in _productVariantRepository.Table on opv.ProductVariantId equals pv.Id
join p in _productRepository.Table on pv.ProductId equals p.Id
where (opv.ceremony_id == ceremony_id) &&
(!o.Deleted) && (opv.IsHireItem == true) &&
(!p.Deleted) &&
(!pv.Deleted) && (opv.ceremony_id == ceremony_id)
select opv,g;
But there is error and I can't select opv and g. if I write select opv;it is ok. but i want to select both table.
How can i do it??
Try using anonymous types i.e.
query1 = from opv in _opvRepository.Table
join o in _orderRepository.Table on opv.OrderId equals o.Id
join g in _graduandRepository.Table on opv.graduand_id equals g.graduand_id
join pv in _productVariantRepository.Table on opv.ProductVariantId equals pv.Id
join p in _productRepository.Table on pv.ProductId equals p.Id
where (opv.ceremony_id == ceremony_id) &&
(!o.Deleted) && (opv.IsHireItem == true) &&
(!p.Deleted) &&
(!pv.Deleted) && (opv.ceremony_id == ceremony_id)
select new { table1Val = opv,
table2Val = g
};

Categories

Resources