C# 具有分组依据和最大日期的Linq查询,获取Id

C# 具有分组依据和最大日期的Linq查询,获取Id,c#,linq,C#,Linq,我很难理解如何完成这个链接查询。我想获得与每个队列号的最大ProcessingStart和ProcessingComplete相关联的Foo.Id 鉴于: public class Foo { public int Id { get; set; } public int QueueNumber { get; set; } public DateTime? ProcessingStart { get; set; } public DateTime? Processi

我很难理解如何完成这个链接查询。我想获得与每个队列号的最大ProcessingStart和ProcessingComplete相关联的Foo.Id

鉴于:

public class Foo
{
    public int Id { get; set; }
    public int QueueNumber { get; set; }
    public DateTime? ProcessingStart { get; set; }
    public DateTime? ProcessingComplete { get; set; }
}

public class Bar
{
    public int QueueNumber { get; set; }
    public int MaxStartId { get; set; }
    public int MaxCompleteId { get; set; }
}

public class QueryData
{

    List<Foo> Foos = new List<Foo>()
    {
        new Foo()
        {
            Id = 1,
            QueueNumber = 1,
            ProcessingStart = new DateTime(2014, 1, 1),
            ProcessingComplete = new DateTime(2014, 1, 3)
        },
        new Foo()
        {
            Id = 2,
            QueueNumber = 1,
            ProcessingStart = new DateTime(2014, 1, 2),
            ProcessingComplete = null
        },
        new Foo()
        {
            Id = 3,
            QueueNumber = 2,
            ProcessingStart = new DateTime(2014, 1, 1),
            ProcessingComplete = new DateTime (2014, 1, 2)
        },
    };

    public void GetMaxProcessingStartCompleteIdPerQueueNumber()
    {
        List<Foo> foos = Foos;

        var query = foos
            .GroupBy(gb => gb.QueueNumber)
            .Select(s => new Bar()
            {
                QueueNumber = s.Key,
                MaxStartId = s.Select(s2 => s2.Id) // select Id where Id is equal to the max ProcessingStart - Cannot implicitly convert IEnum<int> to int
                MaxCompleteId = s.Max(m => m.ProcessingComplete.Value) // select Id where Id is equal to the max ProcessingStart - Cannot implicitly convert DateTime to int
            });
    }

}
你想要:

MaxStartId = s.First(s1 => s1.ProcessingStart == s.Max(s2 => s2.ProcessingStart)).Id,
MaxCompleteId = s.First(s1 => s1.ProcessingComplete == s.Max(m => m.ProcessingComplete.Value)).Id
这应该行得通,但我会用方法代替。不为每条记录执行
Max

MaxStartId = s.MaxBy(s1 => s1.ProcessingStart).Id,
MaxCompleteId = s.MaxBy(s1 => s1.ProcessingComplete).Id

谢谢Selman22,如果我需要用复合密钥而不是Id做同样的事情,那该怎么做呢?我只需要为钥匙的每个部分做两次以上的回答吗?或者有没有更快的方法?
MaxStartId = s.MaxBy(s1 => s1.ProcessingStart).Id,
MaxCompleteId = s.MaxBy(s1 => s1.ProcessingComplete).Id