Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 406
ruedi Avatar asked Sep 12 '26 04:09

ruedi


1 Answers

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))
like image 62
tom.dietrich Avatar answered Sep 13 '26 23:09

tom.dietrich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!