linq string.contains on field of child object list

馋奶兔 提交于 2019-12-04 03:45:39

问题


How can the linq statement here be altered so that it finds the company(s) containing the user with the substring of "third"?

At the moment it only works when searching for the full user name i.e. contains("third user") because it is searching for a match in the list, not the string.

class Company
{
    public Company(List<User> users) { this.Users = users; }
    public List<User> Users { get; set; }
}

class User
{
    public User(string name) { this.Name = name; }
    public string Name { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        List<Company> companies = new List<Company>();
        Company company1 = new Company(new List<User>(){ new User("first user"), new User("second user") });
        Company company2 = new Company(new List<User>() { new User("third user"), new User("fourth user") });
        companies.Add(company1);
        companies.Add(company2);

        companies = companies
                            .Where(company => company.Users.Select(user => user.Name)
                            .Contains("third")).ToList();
    }
}

回答1:


You should call string.Contains on the user.Name:

companies = companies
    .Where(company => company.Users.Any(user => user.Name.Contains("third")))
    .ToList();

See it working online: ideone



来源:https://stackoverflow.com/questions/8429232/linq-string-contains-on-field-of-child-object-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!