日期和值的字典,在LINQ中查找每年的最大日期值

时间:2011-07-05 18:16:54

标签: c# linq

有一个这样的清单:

01/01/2009, 120
04/01/2009, 121
30/12/2009, 520
01/01/2010, 100
04/01/2010, 101
31/12/2010, 540

我需要找到每年的最后一个值,例如结果将是520,540?

2 个答案:

答案 0 :(得分:7)

var lastValues = records.OrderByDescending(r => r.Date)
                     .GroupBy(r => r.Date.Year)
                     .Select(g => g.First().Value);

答案 1 :(得分:1)

class Program
{
    static void Main()
    {
        var list = new[]
        {
            new { Date = new DateTime(2009, 1, 1), Value = 120 },
            new { Date = new DateTime(2009, 4, 1), Value = 121 },
            new { Date = new DateTime(2009, 12, 30), Value = 520 },
            new { Date = new DateTime(2010, 1, 1), Value = 100 },
            new { Date = new DateTime(2009, 4, 1), Value = 101 },
            new { Date = new DateTime(2010, 12, 31), Value = 540 },
        };
        var result = list
            .GroupBy(x => x.Date.Year)
            .Select(g => new { Date = g.Key, MaxValue = g.Max(x => x.Value) });
        foreach (var item in result)
        {
            Console.WriteLine(item);
        }
    }
}