【发布时间】:2016-05-06 03:41:42
【问题描述】:
我不太擅长 linq,所以我在尝试分组和订购时遇到了麻烦。
我的查询目标是,当有人在产品页面上时,我想显示人们也查看过的产品列表。我很确定这个查询是正确的,但我不知道如何转移到 linq 并让它在我的 C# 项目中工作。
我试图更改为 linq 的 Sql Query 是
select pv.ProductId,p.Name, count(*) as 'ProductCount'
from Products p
join ProductVieweds pv
on p.ProductID = pv.ProductId
where UserId in (
select UserId
from ProductVieweds pv
where ProductID = 1 --The 1 in this example is the product the person is viewing.
)
and p.ProductID != 1 --change this
group by pv.ProductId,p.Name
order by 'ProductCount' desc
到目前为止我能做到的。
var sub = (
from p in db.ProductsViewed
where p.ProductId == product.ProductID
select p.UserId).ToList();
var products = (from p in db.Products
join pv in db.ProductsViewed on c.ProductID equals p.ProductId
where p.ProductID != currentProduct.ProductID
where sub.Contains(pv.UserId)
select p).GroupBy(c => c.ProductID).ToList();
PeopleAlsoViewedModel model = new PeopleAlsoViewedModel
{
Products = products,
};
模型
public class PeopleAlsoViewedModel
{
public IEnumerable<Product> Products { get; set; }
}
所以我希望能够按产品分组并按计数排序,但我不知道如何做到这一点,仍然得到一个 IEnumerable。请任何帮助都会很棒,如果您要投反对票,请至少告诉我原因。
【问题讨论】:
-
你的问题有点混乱?可以解释更多细节
-
@NazmulHasan 我不太确定怎么做,但我会试试的。当我使用 .GroupBy(c => c.ProductID) 时,它返回一个 IGrouping
但我想要的是 ToList() 通常返回的是 List。要返回列表,我想我不能使用 .GroupBy()。在发布此问题后进行一些研究后,我发现我可以做到
标签: c# sql-server linq asp.net-mvc-4