0

I'm this expression to search inside a list of objects by a specific property:

var result = myObject.Where(o => o.SearchString.Contains(searchValue));

It works good for a single value. The searchValue is a string passed by the user. The user can pass a single word or many words separeted by spaces. Is there any way to filter the objects that contains any of the passed words?

I could do this with a loop, searching a new word in previous results, but it doesn't seem very elegant.

rbasniak
  • 4,484
  • 11
  • 51
  • 100
  • 1
    @peter-duniho I don't know why this was marked as duplicated. The questin is similiar, but it's not a duplicated. The other question is asking how to check a string for an element of a list of strings. But what I'm wanting to do is filter a collection of objects based on a property with a single LINQ expression. If I use the solution you marked as duplicated, I would have to use a loop, which I stated in the question that I would rather not. – rbasniak Jan 25 '15 at 14:00

1 Answers1

8
myObject.Where(o => words.Any(o.SearchString.Contains))
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • @GrantWinney: Or build a regex. – SLaks Jan 25 '15 at 00:10
  • 1
    Thanks @SLaks, that's exactly what I had in mind, one single line, no loops. Just for those looking at this in future, if you change .Any to .All then the results will include only items that have all matches. – rbasniak Jan 25 '15 at 14:10