-1

我想使用 linq to Entities 将top记录按降序排列Value1

我知道我可以这样写:

MyCollection.OrderByDescending(item => item.Value1).FirstOrDefault();

但是我该如何使用以下方法Top

System.Data.Objects.ObjectQuery.Top(字符串,参数 System.Data.Objects.ObjectParameter[])

4

2 回答 2

5

编辑:这个答案是在问题专门关于 LINQ to SQL 时写的。

System.Data.Objects据我所知,用于实体框架而不是 LINQ to SQL - 但是要在 LINQ to SQL 甚至 LINQ to Objects 中找到前 N 个值,您通常只需使用Take

var query = db.Customers
              .OrderByDescending(c => c.Value1)
              .Take(10);

(我真的鼓励你尝试使用比Value1虽然更有意义的名字......)

编辑:即使在实体框架中,我通常也会Take在 LINQ 查询中使用 - 它是表示前 N 个结果的“LINQ 方式”。如果您真的非常想使用Top文档提供了示例 - 但您应该考虑为什么要使用Top而不是Take. (你没有给我们任何工作的背景。)

于 2013-04-22T08:15:22.563 回答
1

请查看 MSDN 以获取示例http://msdn.microsoft.com/en-GB/library/bb155995.aspx

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    string queryString =
        @"SELECT VALUE product FROM AdventureWorksEntities.Products AS product";

    ObjectQuery<Product> productQuery1 =
        new ObjectQuery<Product>(queryString, context, MergeOption.NoTracking);

    ObjectQuery<Product> productQuery2 = productQuery1.Top("2");

    // Iterate through the collection of Product items. 
    foreach (Product result in productQuery2)
        Console.WriteLine("{0}", result.Name);
}

或者,如果您只是List<T>考虑使用Take()扩展程序。

List<string> strs = new List<strs>() { "1", "2", "3", "4" };
var firstTwo = strs.Take(2);
于 2013-04-22T08:15:08.373 回答