Question

I have some records in database for persons with different due dates. One person can have multiple records with different due dates. I have to write a query to find all records for each person with lowest duedate. I was able to write the query with the exact result when the due dates for a particular person are different. If I have more than one record for a person with same duedate and if that happens to be the lowest date then the query returns multiple rows for the same person. In this case I should get the record with lowest ID (ID being an integer and primary key in the records table). DueDate is a pure Date field and it does not contain time portion.

The below query works perfect except for the above mentioned scenario. allActiveTriggers is a collection of records. I used another query to get this collection.

var activeDistinct = (from at in allActiveTriggers
                         group at by at.Person into dt
                         let date = dt.Min(d => d.DueDate)
                         from t in dt
                         where t.DueDate == date
                         select t).ToList();

Can somebody tell me what I should do to this query ?

Thanks

Was it helpful?

Solution

Just order each group by date and by id, then select first item from ordered group:

from at in allActiveTriggers
group at by at.Person into g
select g.OrderBy(at => at.DueDate).ThenBy(at => at.ID).First()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top