开发者

Linq to entities get first or last from 2million rows

I'm learning LINQ to Entities in C# .NET4.0 Winforms.

I have a MSSQL database table with over 2million rows, eventually more and I need to just pull back the first record or the last record in the database.

I tried getting the last record but it doesn't seem to want to work for me :( It builds okay, but during RunTime I get a

LINQ to Entities does not recognize the method 'StockTraderRobotDT.IntradayFuturesTick       
Last[IntradayFuturesTick](System.Linq.IQueryable`1[StockTraderRobotDT.IntradayFuturesTick])' 
method, and this method cannot be translated into a store expression.            

I'm doing this...

using (DataFeed开发者_StackOverflow中文版Entities db = new DataFeedEntities())
{
   IntradayFuturesTick tick = db.IntradayFuturesTicks.Last();
}

I know it's probably an easy answer but I'm still getting my head around LINQ.

Thanks for your help.

David


You need to sort the results in descending order then use the Take extension method.

using (DataFeedEntities db = new DataFeedEntities())
{
    IntradayFuturesTick tick = db.IntradayFuturesTicks
       .OrderByDescending(x => x.Id)
       .Take(1)
       .Single();
}

You could also use First instead of Take, but I'm not sure if that will return only a single result in the database query.


db.IntradayFuturesTicks.OrderByDescending(x => x.Id).FirstOrDefault();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜