Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically evaluating string conditions in C#

I have a collection of strings. I need to find out from this collection strings which satisfies some condition e.g. that string contains A and B or C. These criteria are specified by the user so 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 the where condition dynamic so that it can work for any input by the user. Is it possible to do this in C# without using any external library. Maybe using Linq or something else which is builtin into .Net framework.

Thanks, Gary

like image 527
gary Avatar asked Jul 06 '10 12:07

gary


3 Answers

Although you don't want to use external libraries, there is one which is just fantastic, and that is PredicateBuilder. Predicate builder allows you to build up a set of predicates to match items against, e.g.:

var predicate = PredicateBuilder.True<string>();
predicate = predicate
    .And(p => p.Contains("a"))
    .And(p => p.Contains("b"));

var matches = items.Where(predicate);
like image 103
Matthew Abbott Avatar answered Oct 16 '22 00:10

Matthew Abbott


If you want to do it on your own, 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 would strongy suggest to use some (lightweight) ready and tested library, that does the conversion from user-strings to runtime-queries for you.

like image 26
Simon D. Avatar answered Oct 15 '22 23:10

Simon D.


alt text
(source: scottgu.com)

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

Check out ScottGu's blog for more examples.

like image 41
Pranay Rana Avatar answered Oct 16 '22 00:10

Pranay Rana