Linq with dynamics "where parameter"

I have this case:

I create an array from a list like this:

String[] parameters = stringParametersToSearch.Split(' ');

The number of parameters can vary from 1 to n and I have to search for objects that in the description field containing all the occurrences of parameters

List<LookUpObject> result = 
        components.Where(o => o.LongDescription.Contains(parameters[0])).ToList<LookUpObject>();

if the parameter is 1 do so, but if they had two or more?

Currently to resolve this situation, I use an IF in which I build the LINQ expression for cases up to five parameters (maximum of real cases).

I can resolve this situation dynamically using LINQ ?

Jon Skeet
people
quotationmark

You either want to use Any or All, depending on whether you want to find objects where all of the parameters match or any of them. So something like:

var result = components
    .Where(o => parameters.Any(p => o.LongDescription.Contains(p)))
    .ToList();

... but change Any to All if you need to.

It's always worth trying to describe a query in words, and then look at the words you've used. If you use the word "any" or "all" that's a good hint that you might want to use it in the query.

Having said that, given the example you posted (in a now-deleted comment), it's not clear that you really want to use string operations for this. If the long description is:

KW=50 CO2=69 KG=100

... then you'd end up matching on "G=100" or "KG=1" neither of which is what you really want, I suspect. You should probably parse the long description and parameters into name/value pairs, and look for those in the query.

people

See more on this question at Stackoverflow