【问题标题】:How to check if a name is contained in another collection如何检查名称是否包含在另一个集合中
【发布时间】:2016-01-13 18:14:43
【问题描述】:

我目前正在做这样的事情:

allSales.Where(x => x.location == "NorthAmerica" && x.CompanyName);

我有一个List<Company>,而 Company 对象有一个 .CompanyName 属性。

我想筛选出包含在 List 集合中的 CompanyName 的销售。

Company 类具有以下属性:

Company
Id
Name

以下不起作用,但这是我想要的:

allSales.Where(x => x.location == "NorthAmerica" && 
       companies.Exists(x => x.Name = x.CompanyName));

公司在哪里列出

【问题讨论】:

标签: c# linq


【解决方案1】:

假设您在变量 companies 中有一个 List<Company>,您可以使用 LINQ Any method 执行以下操作:

allSales
.Where(x =>
    x.location == "NorthAmerica" &&
    companies.Any(c => c.Name == x.CompanyName));

【讨论】:

    【解决方案2】:

    您可以在 List<Company> 对象上使用 Any() 方法和查询来为您的谓词返回 true 或 false。尝试类似:

    allSales.Where(x => x.location == "NorthAmerica" && companies.Any(c => c.Name == x.CompanyName);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-23
      • 1970-01-01
      • 2021-04-05
      • 1970-01-01
      • 2012-03-31
      • 1970-01-01
      • 2017-06-04
      相关资源
      最近更新 更多