下面是一个使用LINQ按照日期差异排序的示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
// 创建一个包含日期的列表
List dates = new List()
{
new DateTime(2022, 1, 1),
new DateTime(2022, 1, 5),
new DateTime(2022, 1, 3),
new DateTime(2022, 1, 2)
};
// 使用LINQ按照日期差异排序
var sortedDates = dates.OrderBy(d => (DateTime.Now - d).Days);
// 打印排序结果
foreach (var date in sortedDates)
{
Console.WriteLine(date.ToString("yyyy-MM-dd"));
}
}
}
在这个示例中,我们首先创建了一个包含日期的列表。然后使用LINQ的OrderBy
方法对日期进行排序,排序规则是根据当前日期和列表中的日期之间的差异天数。最后,我们遍历排序后的结果,打印出日期。
请注意,这个示例中使用了DateTime.Now
来计算日期差异,你也可以根据你的需求修改为其他日期。