修改linq以获得前5个元素

时间:2012-04-12 12:50:11

标签: c# linq

var lastArticles = from a in be.MyTable
                   where a.id == 1
                   join c in be.OtherTable on a.parent equals c.id
                   orderby a.timestamp descending
                   select new { a, cName = c.name};

我需要获得前5个元素。

我是通过

来做的
.Take(5)

但是在linq语句中有没有办法呢?

3 个答案:

答案 0 :(得分:6)

不,您需要使用Skip()Take()作为方法调用。没有LINQ特定的等价物。

var lastArticles = (from a in be.MyTable
                    where a.id == 1
                    join c in be.OtherTable on a.parent equals c.id
                    orderby a.timestamp descending
                    select new { a, cName = c.name }).Take(5);

答案 1 :(得分:1)

linq查询应始终与运行该查询的产品分开。

.Take()会生成结果,因此应该与查询分开并区别开来。

//data query
var lastArticlesQuery = from a in be.MyTable
                   where a.id == 1
                   join c in be.OtherTable on a.parent equals c.id
                   orderby a.timestamp descending
                   select new { a, cName = c.name};

//results of that query at this time
var lastArticles = lastArticlesQuery.Take(5);

答案 2 :(得分:1)

这段代码只是合成糖,它最终将转换为LINQ方法链,看起来像:

var lastArticles = be.MyTable
    .Where(a => a.id == 1)
    .Join(be.OtherTable, a => a.parent, c => c.id,
    (a, c) => new { a, c})
    .OrderByDescending(@t => @t.a.timestamp)
    .Select(@t => new { @t.a, cName = @t.c.name });

因此,为Take()设置一个关键字只会增加sytactic糖,并且还需要重新转换。

简而言之,不,唯一的方法是使用Take()方法。