在Linq中分组3个表

时间:2013-03-14 01:35:45

标签: c# .net sql linq grouping

我是LINQ的新手,在分组我的桌子时遇到了很大麻烦,所以一切都加在一起。我试图让这个显示所有购买超过50美元的客户,即使他们有多个购买。在使用linq的SQL数据库中。这是我到目前为止,请帮助。

 public class TopCustomerVM
 {
    public string Name { get; set; }
    public decimal DollarsSold { get; set; }

    public static List<TopCustomerVM> GetResults()
    {
        ACEEntities db = new ACEEntities();
        return (from c in db.Customers
                join o in db.Orders on c.CustomerId equals o.CustomerId
                join l in db.OrderLines on o.OrderId equals l.OrderId

                into x
                select new TopCustomerVM {                           
                        Name = c.FirstName + c.LastName,
                        DollarsSold = x.Sum(asdf => asdf.UnitCost * asdf.Quantity)
                       })
                       .OrderByDescending(lkj => lkj.DollarsSold)
                       .Where(lkj => lkj.DollarsSold > 50)
                       .ToList();            
    }
}

1 个答案:

答案 0 :(得分:0)

我相信这样的东西会给你想要的输出:

from record in 
    (from c in Customers
    join o in Orders on c.Id equals o.CustomerId
    join ol in OrderLines on o.Id equals ol.OrderId
    let customerAndLine = new { Name = c.FirstName + ' ' + c.LastName, DollarsSold = ol.UnitCost * ol.Quantity }
    group customerAndLine by customerAndLine.Name into grp  
    select new { Name = grp.Key, DollarsSold = grp.Sum(r => r.DollarsSold) })
where record.DollarsSold > 50
orderby record.DollarsSold descending
select record