0

linq クエリの where 句を動的に構築したいと考えています。

名前、性別、場所で検索できる検索オプションがあります。名前のみが入力された場合に次のようなものが得られるように、動的に linq クエリを作成するにはどうすればよいですか。

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

しかし、名前と場所を入力すると、次のようになります。

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

敬具

4

2 に答える 2

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)

(注: このソリューションは、たとえば Entity Framework または であると想定しprofilesていIQueryable<Profile>ますDbSetObjectSet通常のコレクションの場合は、profiles.AsQueryable()代わりに を使用しますprofiles)

于 2013-09-02T11:56:04.833 に答える