简体   繁体   English

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

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

I am trying to execute a select top 1 with ties, but I'm getting trouble to do so.我正在尝试执行一个有关系的选择前 1,但我这样做很麻烦。

I need all the last records of orderdetails, some orders can have more than one article in the list.我需要所有订单明细的最后记录,有些订单列表中可以有不止一篇文章。

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);
           }

Here is a more generic answer, with a custom object it will be easier to explain.这是一个更通用的答案,使用自定义对象会更容易解释。
GroupBy on the field you want order on. GroupBy 在您要订购的字段上。 This way all the row with the same orderID will be together.这样,所有具有相同 orderID 的行都会在一起。
Order Desc on this key, and the first group will be all the row with the max 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