user6313890
user6313890

Reputation:

Filter List using Linq

I have one class:

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

    public DateTime DateTime { get; set; }
}

And one List instance:

var Shops = new List<Shop>()
{
    new Shop()
    {
        Name = "Shop 1",
        DateTime = DateTime.Now
    },
    new Shop()
    {
        Name = "Shop 2",
        DateTime = DateTime.Now.AddDays(-1)
    }
};

I want to filter the Shops list and take only the Shop with the largest (i.e. latest) date.

How can I do this with LINQ?

Upvotes: 0

Views: 73

Answers (3)

scrat.squirrel
scrat.squirrel

Reputation: 3826

var sel = (from shop in Shops orderby shop.DateTime descending select shop).Take(1);

Upvotes: 0

Steve
Steve

Reputation: 216293

An approach could be OrderByDescending and then take the first one

Shop k = S.OrderByDescending(x => x.DateTime).FirstOrDefault();

Upvotes: 1

PiotrWolkowski
PiotrWolkowski

Reputation: 8782

var shop = S.OrderByDescending(s => s.DateTime).FirstOrDefault();

And the result is below:

enter image description here

Upvotes: 1

Related Questions