Search code examples
c#linqselectgroup-by

Group by an array of objects and select based on multiple conditions


I have an array of objects that may contain duplicate records based on some ID.

I am trying to group the objects by ID and from each group pick the record where either status is 3 or with the earliest date (status takes precedence).

ID     Status  Last     LastModified             
1      1       Smith    02/06/2023 04:00 AM   
1      2       Smith    02/06/2023 02:00 AM   
2      1       Jones    02/01/2023 11:24 AM        
3      1       Jack     02/05/2023 02:00 AM   
3      3       Jack     02/06/2023 06:00 AM   

What I would want from a query is to get the following:

ID     Status  Last     LastModified             
1      2       Smith    02/06/2023 02:00 AM   
2      1       Jones    02/01/2023 11:24 AM        
3      3       Jack     02/06/2023 06:00 AM   

I get the records based on date but not sure how to stick the status portion in there:

var filtered = from d in tests.AsEnumerable()
                 group d by d.ID into g
                 select g.OrderBy(p => p.DateTime).FirstOrDefault(); 

This returns:

ID     Status  Last     LastModified             
1      2       Smith    02/06/2023 02:00 AM   
2      1       Jones    02/01/2023 11:24 AM        
3      1       Jack     02/05/2023 02:00 AM   

Solution

  • How about:

    var filtered =
        from d in tests.AsEnumerable()
        group d by d.ID into g
        select g.OrderByDescending(p => p.Status == 3).ThenBy(p => p.DateTime).FirstOrDefault();