Dynamic evaluation of string conditions in C #

I have a rowset. I need to learn from these collection lines that satisfy some condition, for example. this line contains A and B or C. These criteria are set by the user so that they are dynamic. In Linq, it should be something like

List<String> items = new List<string> { "sdsdsd", "sdsd", "abc"}; var query = from item in items where item.Contains("a") && item.Contains("b") || item.Contains("c") select item; 

I want to make a dynamic where clause so that it can work for any user input. Is it possible to do this in C # without using any external library. Perhaps using Linq or something else built into the .Net framework.

Thanks Gary

+6
string c # dynamic linq
source share
3 answers

If you want to do this yourself, start here: Dynamic predicates: http://msdn.microsoft.com/en-us/library/bb513731.aspx Dynamic expression trees: http://msdn.microsoft.com/en-us/ library / bb882637.aspx

I think this is more than you wanted, and will strongly suggest using some (light) ready-made and tested library that does the conversion from user strings to runtime requests for you.

+1
source share

Although you do not want to use external libraries, there is one that is simply fantastic, and that is PredicateBuilder . The predicate constructor allows you to create a set of predicates to match elements, for example:

 var predicate = PredicateBuilder.True<string>(); predicate = predicate .And(p => p.Contains("a")) .And(p => p.Contains("b")); var matches = items.Where(predicate); 
+5
source share

alt text http://www.scottgu.com/blogposts/dynquery/step2.png

Do you need something like this? Use the Linq Dynamic Query Library (download includes examples).

Read more on ScottGu's blog .

+1
source share

All Articles