【问题标题】:How to turn a SQL Query Into Linq? "People who viewed this product also viewed this product."如何将 SQL 查询转换为 Linq? “看过这个产品的人也看过这个产品。”
【发布时间】: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


【解决方案1】:

好的,所以我想出了如何解决我的问题,并认为我应该发布它,以防以后有人阅读。

查询在 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> 变成 List 我把它放在不同的地方,因为多个人可以查看同一个产品,否则它会返回重复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多