使用Linq过滤列表

时间:2016-07-24 15:14:20

标签: c# linq

我有一节课:

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

    public DateTime DateTime { get; set; }
}

一个List实例:

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

我想过滤Shops列表,只使用最大(即最新)日期的Shop

如何使用LINQ执行此操作?

3 个答案:

答案 0 :(得分:1)

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

结果如下:

enter image description here

答案 1 :(得分:1)

方法可以是OrderByDescending,然后是第一个

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

答案 2 :(得分:0)

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