user6313890
user6313890

Reputation:

Linq - Take element with max datetime

I have a class :

public class Shop
{
    public string Name { get; set; }

    public DateTime Date { get; set; }
}

And one instance :

List<Shop> Shops = new List<Shop>()
{
    new Shop()
    {
        Date = new DateTime(2016, 08, 24),
        Name = "Shop1"
    },
     new Shop()
    {
        Date = new DateTime(2016, 08, 23),
        Name = "Shop2"
    },                new Shop()
    {
        Date = new DateTime(2016, 08, 22),
        Name = "Shop3"
    }
};

I want to take only shop with the max datetime. I do :

DateTime MaxDt = Shops.Max(x => x.Date);

Shop S = Shops.Where(x => x.Date == MaxDt).FirstOrDefault();

How to do this in one line ?

Upvotes: 0

Views: 1102

Answers (1)

Igor
Igor

Reputation: 62213

Shop S = Shops.OrderByDescending(x => x.Date).FirstOrDefault();

Upvotes: 3

Related Questions