How to filter a nested list using Linq lambda

I have a class person who has a list of addresses and phones as the following code. In my request, I want a list of people, but not including the address and phone number that are already deleted, but always returns all addresses and phone numbers, even if they are marked as deleted. How can I filter out these nested lists using lambda?

public class Person{
    public int PersonId { get; set; }
    public string Name { get; set; }      
    public virtual ICollection<Address> Addresses { get; set; }
    public virtual ICollection<Phone> Phones{ get; set; }
    public virtual Company Company { get; set; }
}

public class Address{
    public int AddressId { get; set; }
    public string Street { get; set; }      
    public bool Deleted { get; set; }      
    [ScriptIgnore]
    public virtual Person Person { get; set; }
}

public class Phone{
    public int PhoneId { get; set; }
    public string Number{ get; set; }      
    public bool Deleted { get; set; }      
    [ScriptIgnore]
    public virtual Person Person { get; set; }
}

return GetDbSet<Person>()
    .Include("Address")
    .Include("Phones")
    .Where(i => i.Company.CompanyId == company.CompanyId)
    .OrderByDescending(o => o.CreateTime).ToList();
0
source share
1 answer

Just add conditions to the sentence Whereto exclude the remote address and phone, for example:

Where(i => i.Company.CompanyId == company.CompanyId &&
           i.Address.Any(r=> !r.Deleted) &&
           i.Phone.Any(r=> !r.Deleted))
0
source

Source: https://habr.com/ru/post/1673956/


All Articles