ruedi
ruedi

Reputation: 5545

Query with dynamic where clause (concatenated array elements)

I have a dynamic array where the elements should filter elements (where clause) in a linq query.

I use the System.Linq.Dynamic Library mentioned in this questions top answer. If I run:

Dim query = From element In dtImitate.Where("Team = ""Avangers"" Or Team = ""Asgard""")

the query is working. But if I collect the array elements and put them into a string like this:

Public Shared Function CreateDynString(ByRef arr As String()) As String
 Dim a As New StringBuilder
        a.Append("""")
        For Each element In arr
            a.Append("Team = ").Append("""""").Append(element).Append("""""").Append(" or ")
        Next

        Dim b As Integer = a.Length - 4
        a.Remove(b, 4)
        a.Append("""")
        Return a.ToString
End Function

and run the query:

Dim s As String = DynamicStringBuilder.CreateDynString(teamsArray).ToString
Dim query = From element In dtImitate.Where(s)

Nothing happens. My DGV stays empty. Can anyone help me get this query to work and can tell me, why it is not working. If I print s it is "Team = ""Avangers"" Or Team = ""Asgard""". I dont know why it is not working.

Upvotes: 3

Views: 773

Answers (1)

tom.dietrich
tom.dietrich

Reputation: 8347

If you're testing for a property to be in an array, you can use the Contains extension method on IEnumerable, which is probably preferable to building a string. Try this:

Dim query = From element In dtImitate.Where(function (el) teamsArray.Contains(el.Team))

Upvotes: 3

Related Questions