简体   繁体   English

Linq查询分组和最大日期,获取ID

[英]Linq query with group by and max date, get Id

Having trouble wrapping my head around how to accomplish this link query. 无法解决如何完成此链接查询的问题。 I want to get the Foo.Id associated to each of the maximum ProcessingStart and ProcessingComplete, per QueueNumber 我想获取与每个QueueNumber的每个最大ProcessingStart和ProcessingComplete关联的Foo.Id

Given: 鉴于:

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
            });
    }

}

I realize the above two ProcessingStart/ProcessingCOmplete assignments have different errors to them, those are just the two I've tried (unsuccessfully) to craft what is needed. 我意识到上面的两个ProcessingStart / ProcessingCOmplete分配有不同的错误,它们只是我尝试(未成功)设计所需的两个。

My expected outcome with the data provided would be: 通过提供的数据,我的预期结果将是:

Queue     MaxStartId     MaxCompletedId
-----
1     2     1
2     3     3

You want: 你要:

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

This should work but I would use MaxBy method instead. 这应该工作,但我会改用MaxBy方法。 To not perform Max for each record: 不对每个记录执行Max

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM