LINQ由2个属性和创建日期区分

Jey*_*mov 2 c# linq sorting distinct

我有一个包含这样的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; }
}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

假设我发送评级值'4'作为此方法的参数

public IEnumerable<Person> GetList1(int r) {}
Run Code Online (Sandbox Code Playgroud)

并获得一个列表:

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.
Run Code Online (Sandbox Code Playgroud)

如果我发送评级值'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.
Run Code Online (Sandbox Code Playgroud)

xan*_*tos 5

它应该是:

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());
Run Code Online (Sandbox Code Playgroud)

我使用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();
Run Code Online (Sandbox Code Playgroud)

或纯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();
Run Code Online (Sandbox Code Playgroud)