如何在linq中动态构建查询

时间:2013-09-02 11:48:09

标签: vb.net linq

我想为我的linq查询动态构建我的where子句。

我有一个搜索选项,可以搜索姓名,性别和位置。如何动态构建我的linq查询,这样如果只输入名称,我会得到类似的结果:

profiles.where(function(x) x.name = <<nameValue>>)

但是当输入名称时,我会得到类似的位置:

profiles.where(function(x) x.name = <<nameValue>> AND x.location = <<locationValue>>)

亲切的问候

2 个答案:

答案 0 :(得分:3)

您可以使用PredicateBuilder

Dim pred = PredicateBuilder.True(Of Profile)()
If Not String.IsNullOrEmpty(nameValue) Then
    pred = pred.And(Function(x) x.name = nameValue)
End If
If Not String.IsNullOrEmpty(locationValue) Then
    pred = pred.And(Function(x) x.location = locationValue)
End If

Dim query = profiles.Where(pred)

(注意:此解决方案假设profilesIQueryable<Profile>,例如实体框架DbSetObjectSet;如果它只是普通集合,请使用{{1}而不是profiles.AsQueryable()

答案 1 :(得分:0)

如果您的条件始终为AND,且永远不会OR,那么您可以在步骤中构建查询:

Dim query = profiles.AsQueryable()

If Not String.IsNullOrEmpty(nameValue) Then
    query = query.Where(Function(x) x.name = nameValue)
End If

If Not String.IsNullOrEmpty(locationValue) Then
    query = query .Where(Function(x) x.location = locationValue)
End If

Return query.ToList()

LINQ查询执行被延迟,因此只有在需要结果或您明确要求它执行时才执行它,例如调用ToList()方法。