EDIT: Based on one of the posts below, i figured out how to write it. Answer is at the end of this post.
I have a store… and one of the dropdowns allow you to sort the products by popularity (items that are most purchased, show up first).
I know how to write this in SQL, but i’m failing miserably in LINQ. Can someone translate this for me? Hopefully if I see enough of these examples, i’ll get better at doing it myself…
I simply want to bring back all the items, but in order of popularity. You can tell which are most popular by seeing how many times the itemId comes up in the “OrderDetails” table.
select i.*
from items i
left outer join (
select od.itemid, ct = COUNT(1)
from orderdetails od
join orders o on od.orderid = o.orderid
where o.ordersubmitteddate is not null
group by od.itemid
) pop on pop.itemid = i.itemid
order by pop.ct desc, i.name
—— ANSWER BELOW ——-
Here’s the answer, I write one query first to determine which “items” i want to show… and then I write a second query to order it….
var items = db.Items.Where("STUFF");
items = from i in items
join pop in (
from od in db.OrderDetails
where od.Order.OrderSubmittedDate != null
group od by od.ItemId into g
select new { ItemId = g.Key, Ct = g.Count() }
) on i.ItemId equals pop.ItemId into pop_join
from x in pop_join.DefaultIfEmpty()
orderby x.Ct descending, i.Name
select i;
Well, you could try
This should definitely get you in the right direction, but I can’t guarantee this even compiles. The idea is that you can nest queries in LINQ to SQL.