gpt4 book ai didi

c# - LINQ 通过 2 个属性和创建日期来区分

转载 作者:行者123 更新时间:2023-12-02 18:09:32 24 4
gpt4 key购买 nike

我有一个包含 Person 模型的列表,如下所示:

public class Person
{
[Key]
public int Id { get; set; }
public int Rating1 { get; set; }
public int Rating2 { get; set; }
public DateTime CreateDate { get; set; }
}

Rating1 永远不等于Rating2

问题:

如何获取 Rating1Rating2 等于给定评级值的列表,以及该列表中最后创建的元素?

我通过示例解释我的观点。假设这里是列表:

Rating1    Rating2    CreateDate
4 8 2013-08-15 05:12:00
9 4 2013-08-15 07:12:00
8 4 2013-08-15 08:12:00
5 20 2013-08-15 09:12:00
20 4 2013-08-15 10:12:00
20 5 2013-08-15 11:12:00
4 9 2013-08-15 12:12:00

假设我将评级值“4”作为参数发送到此方法

public IEnumerable<Person> GetList1(int r) {}

并获取列表:

8          4          2013-08-15 08:12:00 //because there are many [4 and 8] couples, but this created last.
4 9 2013-08-15 12:12:00 //because there are many [4 and 9] couples, but this created last.
20 4 2013-08-15 10:12:00 //because there is one [4 and 20] couple, this also created last.

如果我将评级值“20”作为参数发送给 GetList1() 方法,我想获取一个列表:

 20         5          2013-08-15 11:12:00 //because there are many [20 and 5] couples, but this created last.
20 4 2013-08-15 10:12:00 //because there is one [20 and 4] couple, this also created last.

最佳答案

应该是:

int r = 4; // your rating

var res = from p in lst
where p.Rating1 == r || p.Rating2 == r
group p by new { Min = Math.Min(p.Rating1, p.Rating2), Max = Math.Max(p.Rating1, p.Rating2) };

var res2 = res.Select(p => p.OrderByDescending(q => q.CreateDate).First());

我使用 Math.MinMath.Max 将最低评分设为第一个,将最大评分设为第二个。因此 4, 8 相当于 8, 4

或者,(或多或少等效):

var res = from p in lst
where p.Rating1 == r || p.Rating2 == r
group p by new { Min = Math.Min(p.Rating1, p.Rating2), Max = Math.Max(p.Rating1, p.Rating2) } into q
select q.OrderByDescending(s => s.CreateDate).First();

或纯 LINQ(但可读性较差)

var res = from p in lst
where p.Rating1 == r || p.Rating2 == r
group p by new { Min = Math.Min(p.Rating1, p.Rating2), Max = Math.Max(p.Rating1, p.Rating2) } into q
select (from s in q orderby s.CreateDate descending select s).First();

关于c# - LINQ 通过 2 个属性和创建日期来区分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18256251/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com