我真的不太擅长linq,所以我在分组和排序时遇到了麻烦。
我的查询目标是,当有人在产品页面上时,我想显示人们也查看过的产品列表。我确信这个查询是正确的,但我不知道如何转移到linq并使其在我的C#项目中工作。
尝试更改为linq的Sql查询是
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<产品>。任何帮助都会很棒,如果你要投反对票,至少告诉我为什么。
好的,所以我想好了如何解决我的问题,并认为我应该发布它,以防以后有人读到它。
C#中的查询将如下所示
var products = (from c in db.Products
join p in db.ProductsViewed on c.ProductID equals p.ProductId
where c.ProductID != CurrentProduct.ProductID
where sub.Contains(p.UserId)
group c by c.ProductID into productGrouped
orderby productGrouped.Key
select productGrouped).SelectMany(group => group.Distinct()).ToList();
SelectMany()将List<I分组<键,元素>>到List<Element>我之所以将其区分开来,是因为多个人可以查看同一个产品,否则它会返回重复的产品。