Swapna
Swapna

Reputation: 403

how to bind only 10 latest records to the model in C#

im getting several records in the model, i just need only ten latest records order by descending time.i just need to show only 10 records in the table.how to write linq query so that i can get only 10 records.and in foreach loop also it should not bind more than 10 times.

code

   public ActionResult AssetTrack()
            {
        model.AddRange(getAssetDetails("0000acfffe588041"));
        model= model.OrderByDescending(t => t.time).Take(10).ToList();
        return View(model);
            }

     WebRequest req = WebRequest.Create(@"https://example.com");
                    req.Method = "GET";
                    req.Headers["Authorization"] = "Basic " + "abc@123==";
                    HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
                    var encoding = resp.CharacterSet == "" ? Encoding.UTF8 : Encoding.GetEncoding(resp.CharacterSet);
                    using (var stream = resp.GetResponseStream())
                    {
                        var reader = new StreamReader(stream, encoding);
                        var responseString = reader.ReadToEnd();
                        List<AssetDetail> Pirs = Newtonsoft.Json.JsonConvert.DeserializeObject<List<AssetDetail>>(responseString);

                        foreach (var item in Pirs)
                        {
                            byte[] data = Convert.FromBase64String(item.dataFrame.ToString());
                            AssetTrackerViewModel assetModel = new AssetTrackerViewModel();
                            assetModel.deviceid = deviceID;
                            assetModel.longitude = Convert.ToString(Encoding.UTF8.GetString(data).Substring(4));
                            assetModel.latitude = Convert.ToString(Encoding.UTF8.GetString(data).Substring(4));
                            assetModel.time = TimeZoneInfo.ConvertTimeFromUtc(item.timestamp, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")).ToString();
                            model.Add(assetModel);
                        }
                    }

Upvotes: 0

Views: 166

Answers (2)

Christos
Christos

Reputation: 53958

You could just use the Take method.

Since from you question isn't too clear where you want to apply this, below I provide two snippets:

model = model.OrderByDescending(x => DateTime.Parse(x.time))
             .Take(10)
             .ToList();

var Pirs = Newtonsoft.Json.JsonConvert
                          .DeserializeObject<List<AssetDetail>>(responseString)
                          .OrderBy(assetDetail=>assetDetail.time)
                          .Take(10);

If you want to read about this method, please have a look here.

Upvotes: 2

Sajeetharan
Sajeetharan

Reputation: 222692

use linq,

var result = Pirs.OrderByDescending(t => t.time).Take(10).ToList();

Upvotes: 1

Related Questions