【问题标题】:Creating a linq condition using a list使用列表创建 linq 条件
【发布时间】:2021-07-21 20:09:21
【问题描述】:

我有一个用于从数据库中获取列表的方法。

public List<SelectedCustomers> GetCustomers(List<int> customerNumbers)
{
   var customers=_context.Customers.Where(?).Select(i=> new SelectedCustomers() {}).ToList()
}

我想从用户提供客户编号的客户数据库中检索信息。数据库中的客户列表中大约有十万个客户。我不希望该方法每次调用时都获取整个列表并搜索它,这需要太多的努力。但是,我不知道如何在 where() 中使用列表。

总而言之,我不想拉出我想要的所有列表并在列表中搜索用户请求的值,我想使用直接来自用户的列表进入数据库并给我这些信息客户。

我希望我能解释一下。感谢您的帮助。

【问题讨论】:

  • .Where(customer=&gt;customerNumber.Contains(customer.ID)) 生成WHERE customer.ID in (1,4,5,8,9,....)
  • 你的意思是:Where(customer =&gt; customerNumbers.Contains(customer.Number))? (当然,为了清楚起见,将您的 customerNumber 重命名为 customerNumbers。)
  • 是的,@JonSkeet 在customerNumber 中有多个客户编号,所以我将名称编辑为customerNumbers。谢谢

标签: c# list linq where-clause


【解决方案1】:

尝试类似(未测试)

public List<SelectedCustomers> GetCustomers(List<int> customerNumbers)
{
   var customers=_context.Customers.Where(x =customerNumbers.Contains(x.customerNumber)
                       .Select(i=> new SelectedCustomers() {}).ToList()
}

这相当于 SQL IN ()

【讨论】:

    【解决方案2】:

    试试这个:

    var customers = _context.Customers.Where(c => customerNumber.Contains(c.CustomerId)).Select(i => new SelectedCustomers() { }).ToList()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-23
      • 2013-05-29
      • 2023-02-02
      • 1970-01-01
      • 2012-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多