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
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);
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.
(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With