views:

105

answers:

3

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

+1  A: 

alt text

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

Check out ScottGu's blog for more examples.

Pranay Rana
+5  A: 

Although you don't want to use external libraries, there is one which is just fantastic, and that is PredicateBuilder (http://www.albahari.com/nutshell/predicatebuilder.aspx). 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);
Matthew Abbott
A: 

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.

Simpzon