Home > OS >  How do I get the object with the second latest date from a collection of objects
How do I get the object with the second latest date from a collection of objects

Time:10-09

I have a list of objects and each object has an AcceptanceDate property which is of type DateTime.

I want to retrieve the Object with the second latest date in the list.

Is there any way of doing that?

[
   {
        "number": "X76-M1-20/2",
        "AcceptanceDate": "2020-07-30T00:00:00Z",
        "type": "Done",
    
    },

    {
        "number": "X75-M1-18/2",
        "AcceptanceDate": "2018-03-04T00:00:00Z",
        "type": "Done",
    
    },
    {
        "number": "X66-M1-20/1",
        "AcceptanceDate": "2020-02-12T00:00:00Z",
        "type": "Done",
    
    
    },
    {
        "number": "X77-M1-17/1",
        "AcceptanceDate": "2017-02-14T00:00:00Z",
        "type": "Done",
    
    } 
]

In This example I want to return the object with number : X66-M1-20/1

I Tried to follow this Linq: How to get second last

But it's not working in my case because it a list of objects.

CodePudding user response:

try this

var jd = JsonConvert.DeserializeObject<List<Data>>(json); 
var item =jd.OrderBy(j =>j.AcceptanceDate ).TakeLast(2).FirstOrDefault();

output

Number  X66-M1-20/1
AcceptanceDate  2020-02-12
Type    Done

class

public class Data
{
    public string Number { get; set; }
    public DateTime AcceptanceDate { get; set; }
    public string Type { get; set; }
}

UPDATE

Since PO wants 2 last objects I can recommend this code

var jd = JsonConvert.DeserializeObject<List<Data>>(json); 
var items =jd.Where(i=> i.Type=="Done").OrderBy(j =>j.AcceptanceDate).TakeLast(2).ToList();

if (items!= null && items.Count >=2)
{
var secondLastItem=items[0];
var lastItem=items[1];
}

output

    X66-M1-20/1 2020-02-12  Done  //secondLastItem
    X76-M1-20/2 2020-07-30  Done  //lastItem
  • Related