繁体   English   中英

如何将 SELECT TOP 1 WITH TIES 查询转换为 LINQ C#?

[英]How to convert SELECT TOP 1 WITH TIES query to LINQ C#?

我正在尝试执行一个有关系的选择前 1,但我这样做很麻烦。

我需要所有订单明细的最后记录,有些订单列表中可以有不止一篇文章。

var qry = (from ordd in db.OrderDetails
           join ord in db.Orders on ordd.OrderId equals ord.OrderId
           join cust in db.Salespersons on ord.SalespersonId equals cust.SalespersonId
           join comp in db.Companies on ord.CompanyId equals comp.CompanyId
           join pro in db.Products on ordd.ProductId equals pro.ProductId                              
           where (ord.OrderId == ordd.OrderId && pro.ProductId == ordd.ProductId)
           orderby ordd.OrderId descending
           select new { ordd })
           .Distinct()
           .ToList();

           foreach (var item in qry)
           {
               dt.Rows.Add(item.ordd.Reference, 
                           item.ordd.Quantity,
                           item.ordd.Description, 
                           item.ordd.Price, 
                           item.ordd.Price * item.ordd.Quantity);
           }

这是一个更通用的答案,使用自定义对象会更容易解释。
GroupBy 在您要订购的字段上。 这样,所有具有相同 orderID 的行都会在一起。
此键上的顺序描述,第一组将是具有最大 orderID 的所有行

var input = new Foo[] {
    new Foo{GroupId=1,Label="a" },
    new Foo{GroupId=2,Label="b" },
    new Foo{GroupId=3,Label="c" },
    new Foo{GroupId=3,Label="d" },
    new Foo{GroupId=2,Label="e" },
    new Foo{GroupId=4,Label="Bar" },
    new Foo{GroupId=4,Label="Bar" }
};

var result = input.Where(x => x.Label!="Bar")         //-> { a, b, c, d, e }
                    .GroupBy(x => x.GroupId)          //-> {1: a} {2: b, e} {3: c, d}
                    .OrderByDescending(x=> x.Key)     //-> {3: c, d} {2: b, e} {1: a} 
                    .First();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM