Query with dynamic where clause (concatenated array elements)

dynamic-linq linq vb.net

Question

I have a dynamic array whose items may be filtered by a linq query (where clause).

I useSystem.Linq.Dynamic The top answer to question zzz-12 mentions a library. If I go forward:

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

The search is successful. However, if I compile the items in the array and combine them into the following string:

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

execute the query as well

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

Nothing occurs. My DGV remains vacant. Can somebody explain me why this query isn't working and help me get it to work? The printings it is"Team = ""Avangers"" Or Team = ""Asgard""" . I have no idea why it isn't functioning.

1
3
5/23/2017 10:26:23 AM

Accepted Answer

You may use the to check if a property is present in an array.Contains extension approach toIEnumerable , which is probably better than creating a string. Do this:

Dim query = From element In dtImitate.Where(function (el) teamsArray.Contains(el.Team))
3
9/11/2014 12:05:14 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow