gpt4 book ai didi

string - linq string.contains on 子对象列表的字段

转载 作者:行者123 更新时间:2023-12-01 02:40:53 26 4
gpt4 key购买 nike

如何更改此处的 linq 语句,以便找到包含子字符串为“third”的用户的公司?

目前它仅在搜索完整用户名时有效,即 contains("third user") 因为它正在搜索列表中的匹配项,而不是字符串。

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 user.Name :

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

在线查看: ideone

关于string - linq string.contains on 子对象列表的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8429232/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com