gary
gary

Reputation: 289

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

Upvotes: 6

Views: 3299

Answers (3)

Pranay Rana
Pranay Rana

Reputation: 176896

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.

Upvotes: 1

Matthew Abbott
Matthew Abbott

Reputation: 61589

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);

Upvotes: 5

Simon D.
Simon D.

Reputation: 4481

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.

Upvotes: 1

Related Questions