简体   繁体   中英

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

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.

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. To not perform Max for each record:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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