简体   繁体   中英

retrieve 5 last records from table by C#

I want to retrieve 5 last record of one of my tables in Data base by C# code.I don't want using query in Sql server. in my code I want to retrieve 5 last records in tt.what do I do? now it retrieves all of the Records

            var temp = db.Positions.Where(P => P.DeviceID == device.ID);
            List<Position> tempPositions = FilterPosition(temp.ToList<Position>());
            var tt = FilterStops(tempPositions, new TimeSpan(0, 30, 0), 100);
            List<JsonDevicePositionModel> returnPositions = (

                                          from p in tt

                                             select new 
                                                 JsonDevicePositionModel

                                             {
                                                 DeviceID = p.Position.DeviceID,
                                                 Latitude = p.Position.Latitude,
                                                 Longitude = p.Position.Longitude,
                                                 SerialNumber = p.Position.Device.SerialNumber,

                                                 Speed = p.Position.Speed,


                                             }).ToList(); 

            //    }
            return Json(returnPositions, JsonRequestBehavior.AllowGet);

        }

如果您不必担心性能,则可以使用扩展方法Take of Enumerable类:

var tt = FilterStops(tempPositions, new TimeSpan(0, 30, 0), 100).Take(5);

你可以试试 ...

from p in tt.GetRange(tt.Count - 6, 5)

另一种可能性:来自tt.Skyp(tt.Count-5)中的p.Take(5)

var full = FilterStops(tempPositions, new TimeSpan(0, 30, 0), 100);
var tt= full.Skip(full.Count - 5);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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