linq查询与动态where子句

时间:2012-04-13 15:43:01

标签: c# asp.net vb.net linq c#-4.0

我需要使用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评估字符串中的每个值 提前谢谢。

2 个答案:

答案 0 :(得分:3)

在这种情况下,我会选择Inner Join。如果我使用Contains,则会Iterate unnecessarily 6次despite of the fact that there is just one match

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次!!!

答案 1 :(得分:1)

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