JHDesigne
JHDesigne

Reputation: 3

How to sort the collection List by the latest(datetime) field?

I have a list of fields and I want to sort by the Latest date a field type datetime

foreach (var item in PList)
{                        
      SchemaPermis schemaPermis = new SchemaPermis();

      schemaPermis.PE_NUMERO = item.PE_NUMERO;
      schemaPermis.PE_REFERENCE = item.PE_REFERENCE;
      schemaPermis.PE_COUT_PREVU = item.PE_COUT_PREVU;
      schemaPermis.PE_DATE_FIN = item.PE_DATE_FIN;
      schemaPermis.PE_AUTRE_OBJET = item.PE_AUTRE_OBJET;

      PermisList.Add(schemaPermis);                     
}

I need to be able to sort the collection List by the latest(datetime) field.

Upvotes: 0

Views: 210

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460058

Do you want to sort PList or PermisList? However, you can use LINQ's OrderBy or OrderByDescending:

var orderedPermaList = PermisList
    .OrderByDescending(p => p.PE_DATE_FIN);

If you need a List<SchemaPermis> use ToList().

But what means latest at all? Do you you want to sort descending by this datetime field or do you want to get the latest SchemaPermis object from the list?

If you want a single object, the latest SchemaPermis in the list:

SchemaPermis lastPerma = PermisList
    .OrderByDescending(p => p.PE_DATE_FIN)
    .First();

If you want to modify the original list instead of creating a new one (with ToList) you can use the overload of List.Sort, you need to multiply with -1 to get descending order:

permaList.Sort((p1, p2) => -1 * p1.PE_DATE_FIN.CompareTo(p2.PE_DATE_FIN));

Upvotes: 3

Nahuel Ianni
Nahuel Ianni

Reputation: 3185

You can do something like this:

var orderedList = PermisList.OrderBy(item => item.LatestDate);

Upvotes: 0

Related Questions