简体   繁体   中英

How to construct dynamic LINQ query string be for a query that looks like *abc*def*

I am using Dynamic LINQ for one of my projects to filter arrays. Library can be downloaded from NuGet Gallery link or Codeplex link . I am using version 1.0.6 from NuGet link. It is the same as LINQ but the condition can be specified using strings. Eg : myArray.Where(myDynamicQueryString)

I build QueryStrings on the fly based on left, right expressions and operators. For example, if my query is

  1. abc < 3, My dynamic query string will be (abc < 3)
  2. xyz == 5.0, myDynamicQueryString will be (xyz = 5)
  3. def == "Name", myDynamicQueryString will be (def = "Name")
  4. var == "Str*", myDynamicQueryString will be (var.StartsWith("Str"))
  5. var == "*Str", myDynamicQueryString will be (var.EndsWith("Str"))
  6. var == "*Str*", myDynamicQueryString will be (var.Contains("Str"))

Now, what should query string be for a query like *abc*def*?

I know it means, it could start with anything, end with anything and have anything in between abc and def, but abc and def should appear in that particular order. But, how do I translate that into a query representation using StartsWith/EndsWith/Contains(These are the ones I know, Please let me know if there are any others I can use)

It looks like what you need is IndexOf . This returns the starting index of the substring, if it exists, otherwise -1.

var.Contains("abc") && var.Contains("def") && 
   var.IndexOf("abc") > var.IndexOf("def")

For example, if we use the string XabcXdefXabc , var.IndexOf("abc") will yield 1 and var.IndexOf("def") will yield 5 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM