繁体   English   中英

带有动态where子句的linq查询

[英]linq query with dynamic where clause

我需要使用LINQ做与t-sql语句等效的操作:

SELECT * FROM mytable WHERE idnumber IN('1', '2', '3')

所以在LINQ中,我有:

Dim _Values as String = "1, 2, 3"
Dim _Query = (From m In mytable Where idnumber = _Values Select m).ToList()

不知道如何处理_Values以使idnumber评估字符串中的每个值。
提前致谢。

在这种情况下,我将参加Inner Join 如果我使用了Containsdespite of the fact that there is just one match ,但它会Iterate unnecessarily 6次。

C#版本

var desiredNames = new[] { "Pankaj", "Garg" }; 

var people = new[]  
{  
    new { FirstName="Pankaj", Surname="Garg" },  
    new { FirstName="Marc", Surname="Gravell" },  
    new { FirstName="Jeff", Surname="Atwood" }  
}; 

var records = (from p in people 
               join filtered in desiredNames on p.FirstName equals filtered  
               select p.FirstName
              ).ToList();

VB.Net版本

Dim desiredNames = New () {"Pankaj", "Garg"}

Dim people = New () {New With { _
    .FirstName = "Pankaj", _
    .Surname = "Garg" _
}, New With { _
    .FirstName = "Marc", _
    .Surname = "Gravell" _
}, New With { _
    .FirstName = "Jeff", _
    .Surname = "Atwood" _
}}

Dim records = ( _
    Join filtered In desiredNames On p.FirstName = filtered).ToList()

容器的缺点

假设我有两个列表对象。

List 1      List 2
  1           12
  2            7
  3            8
  4           98
  5            9
  6           10
  7            6

使用Contains,它将搜索List-2中的每个List-1项目,这意味着迭代将发生49次!

Dim _Values as String = "1, 2, 3"
Dim _Query = (From m In mytable Where _Values.Split(", ").Contains(m.idnumber) Select m).ToList()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM