Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching Multiple Fields with LINQ Contains or Other

Tags:

c#

linq

I'm using LINQ to search multiple fields on a single phrase and I'm using Contains() to do this. Up until today, when I noticed that the find method isn't working correctly.

So I'd like to be able to search each of the fields where there is any match. I've done some searching on Google and through SO and found suggestions of using Any()? Does anyone have any suggestions?

var l = _getData().Select(_marshallData).ToList();
            return l.Where(x => x.Name.Contains(what) || x.Pumpkin.Contains(what) || x.Orange.Contains(what) || x.Tomato.Contains(what)).ToList();

Please excuse the stupid field names, I've had to change them for confidentiality.

like image 806
dooburt Avatar asked Jun 07 '13 22:06

dooburt


1 Answers

Since you're materializing the data already you could do this:

var l = _getData().Select(_marshallData).AsEnumerable();
return l.Where(x => new[] { x.Name, x.Pumpkin, x.Orange, x.Tomato }.Any(s => s.Contains(what)));

But if you're using an ORM (like Entity Framework) this trick probably won't work (since there's a good chance this can't be converted to a SQL expression). In this case, you're original solution is fine, but it would probably be better to do this before you materialize the data.

return _getData()
    .Where(x => 
        x.Name.Contains(what) || x.Pumpkin.Contains(what) || 
        x.Orange.Contains(what) || x.Tomato.Contains(what))
    .Select(_marshallData)
    .AsEnumerable();

Of course the field names here might be different, since the parameter x is probably a different type. Without further information, it's up to you to write this filter correctly.

Note that in both examples, I've eliminated the calls to ToList. Unless you absolutely need the result to a List<T> this is probably unnecessary.

like image 175
p.s.w.g Avatar answered Oct 05 '22 06:10

p.s.w.g