Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

linq string.contains on field of child object list

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();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...