how to filter nested list using Linq lambda

2019-08-17 05:16发布

I have a class person which has a list of addresses and phones as the follow code. In my query I want a list of person but not including the address and phone that are already deleted, but is always returning all addresses and phones even they flag as deleted. How could I filter those 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();

1条回答
混吃等死
2楼-- · 2019-08-17 05:55

Just add conditions in your Where clause to exclude deleted address and phone like:

Where(i => i.Company.CompanyId == company.CompanyId &&
           i.Address.Any(r=> !r.Deleted) &&
           i.Phone.Any(r=> !r.Deleted))
查看更多
登录 后发表回答