这就是你的意思?(使用 Linq)
var merged = list1.Union(list2).OrderByDescending(d => d.Date);
请注意,这只有在两个列表类型相同时才有可能。其他注意,这将返回一个 IEnumerable,而不是一个新的 List,因此每次枚举它时,都会计算合并。如果你想创建一个新的 List 来防止这种情况,你必须在最后调用 ToList() ,但是如果你有很大的列表,这可能会在性能上非常不理想。
示例程序:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Lists
{
class Program
{
static void Main(string[] args)
{
var list1 = new List<DateItem>
{
new DateItem{Date = DateTime.UtcNow.AddDays(-2), Name = "The day before yesterday" },
new DateItem{Date = DateTime.UtcNow.AddDays(1), Name = "Tomorrow" }
};
var list2 = new List<DateItem>
{
new DateItem{Date = DateTime.UtcNow.AddDays(2), Name = "The day after tomorrow" },
new DateItem{Date = DateTime.UtcNow.AddDays(-1), Name = "Yesterday" },
new DateItem{Date = DateTime.UtcNow, Name = "Today" }
};
var merged = list1.Union(list2).OrderByDescending(d => d.Date);
foreach (var day in merged)
{
Console.WriteLine(day.Name);
}
}
}
class DateItem
{
public DateTime Date { get; set; }
public string Name { get; set; }
}
}