linq string.contains在子对象列表的字段上 [英] linq string.contains on field of child object list
本文介绍了linq string.contains在子对象列表的字段上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何更改此处的linq语句,以便找到包含用户的公司(子字符串为"third")的公司?
How can the linq statement here be altered so that it finds the company(s) containing the user with the substring of "third"?
目前,它仅在搜索完整的用户名(即contains(第三用户"))时有效,因为它正在搜索列表中的匹配项,而不是字符串.
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();
}
}
推荐答案
您应致电 string.Contains
:
You should call string.Contains
on the user.Name
:
companies = companies
.Where(company => company.Users.Any(user => user.Name.Contains("third")))
.ToList();
查看其在线运行情况: ideone
See it working online: ideone
这篇关于linq string.contains在子对象列表的字段上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文