您可以按照Date 对条目进行分组,然后使用MinBy 选择具有最低Priority 的条目。
sequence.GroupBy(d => d.Date).Select(g => g.MinBy(d => d.Priority));
MinBy 在System.Linq 中开箱即用,因为.NET 6。它也可以取自MoreLinq,但请注意,在MoreLinq 中,返回类型是一个包含所有具有相同最低优先级的值的可枚举,因此您需要使用SelectMany:
sequence.GroupBy(d => d.Date).SelectMany(g => g.MinBy(d => d.Priority));
.NET 6 演示:
using System;
using System.Linq;
var sequence = new DayResponse[] {
new() { Date = new DateTime(2000, 01, 01), Priority = 1},
new() { Date = new DateTime(2001, 01, 01), Priority = 2},
new() { Date = new DateTime(2001, 01, 01), Priority = 5},
};
var distinct = sequence.GroupBy(d => d.Date).Select(g => g.MinBy(d => d.Priority));
foreach (var x in distinct)
{
Console.WriteLine($"DayResponse: Date = {x.Date}, Priority = {x.Priority}");
}
public class DayResponse
{
public DateTime Date { get; set; }
public int Priority { get; set; }
}
可在此处获取:https://dotnetfiddle.net/SLnkSr