Search code examples
c#.netlistlinq

Filter a list based on a property that is inside another list it contains


I have an order object with its partial class containing changes history:

public class SomeOrder
{
    public string SomeOrderNumber { get; set; }
    public string Status { get; set; }
    public IEnumerable<SomeOrderChangesHistory> ChangesHistory { get; set; }
}

public partial class SomeOrderChangesHistory
{
    public string PropertyName { get; set; }
    public string OldValue { get; set; }
    public string NewValue { get; set; }
    public DateTime DateTimeUtc { get; set; }
    public string UserName { get; set; }
}

I'll be getting a list of SomeOrder and I want to filter out the orders if they are updated by api user.

The orders updated by api user will have one or more SomeOrderChangesHistory object in the ChangesHistory list with api user value in the UserName property (in SomeOrderChangesHistory object).

How do I accomplish this?


Solution

  • Based on @NetMage's excellent comment:

    var ordersNotUpdatedByAPIUser = orders
                                    .Where(o => !o.ChangeHistory.Any(ch => ch.UserName == "api user"))
                                    .ToList()
    

    It will filter out all the orders updated by api user which is exactly what I want.