Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 日期和值字典,查找LINQ中每年最大日期的值_C#_Linq - Fatal编程技术网

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

C# 日期和值字典,查找LINQ中每年最大日期的值,c#,linq,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 我需要找到每年的最后一个值,例如,结果是520540?列表是如何用代码构造的?当然可以。选择(g=>g.last().value)@Andrew我们不知道初始顺序,因此需要对其进行排序,因此使用First()和OrderByDescending()或Last()和OrderBy()应该可

请列出如下列表:

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

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

列表是如何用代码构造的?当然可以。选择(g=>g.last().value)@Andrew我们不知道初始顺序,因此需要对其进行排序,因此使用
First()
OrderByDescending()
Last()
OrderBy()
应该可以。这是每年的最大值(也很有用!),我只想要每年的最后一个值。
var lastValues = records.OrderByDescending(r => r.Date)
                     .GroupBy(r => r.Date.Year)
                     .Select(g => g.First().Value);
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);
        }
    }
}