2011-12-08 76 views
2

如何修改linq語句,以便找到包含用戶的公司的子字符串爲「third」?linq string.contains子對象列表字段

目前它僅在搜索完整用戶名(即包含(「第三個用戶」))時起作用,因爲它在列表中搜索匹配項,而不是字符串。

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

回答

3

你應該在user.Name呼籲string.Contains

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

看到它聯機工作:ideone

+0

很好,謝謝。我最初嘗試在user.Name上調用Contains,但它不會編譯。我現在看到'Any'關鍵字是缺失的成分,我將在此處詳細閱讀。 – user1087450

+0

這不是關鍵字 - 它是一種擴展方法。請參閱文檔:['Enumerable.Any'](http://msdn.microsoft.com/zh-cn/library/bb534972.aspx) –