如何使用Linq lambda过滤嵌套列表 [英] how to filter nested list using Linq lambda

查看:161
本文介绍了如何使用Linq lambda过滤嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个班级人员,其地址和电话列表如下面的代码。
在我的查询中,我想要一个人的列表,但不包括已经删除的地址和电话,但总是返回所有地址和电话,即使他们标记为删除。如何使用lambda过滤这些嵌套列表?

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();


推荐答案

只需在其中子句排除删除的地址和手机,如:

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))

这篇关于如何使用Linq lambda过滤嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆