1

I've a table that contains details of Members. The Name field will be having values like "John Antony", "Sarah Ann Mathew", "Josh John".

How do I select all members who are having names containing any of the words in "John, Ann, Mathew".

I've tried implementations like db.members.Where(m=>names.Contains(m.Name)); but the issue is that I am trying to match any word in m.Name.

Thanks in advance.

Libin TK
  • 1,477
  • 2
  • 25
  • 46

1 Answers1

4

If you make names a collection of strings, like this {"John", "Ann", "Mathew"}, you can rewrite your query as follows:

var res = db.members.Where(m=>names.Any(n => m.Name.Contains(n)));
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    just watch out for case sensitivity – Miles Mar 13 '14 at 18:15
  • @Miles Yes. found that issue `"John"` matches `"jonathan swift"` too. Is there any way to match the whole word or match case? – Libin TK Mar 13 '14 at 18:18
  • 2
    @LibinTK Here is [an answer about case sensitivity](http://stackoverflow.com/a/3360808/335858). Exact matches are a little trickier - you may want to to use EF for fast pre-filtering, and then do additional filtering in memory with regex. Regex lets you add `\b` on both sides of a name for word boundaries - something you cannot do with EF's `Contains`. – Sergey Kalinichenko Mar 13 '14 at 18:23
  • @RalphLavelle Thanks! – Sergey Kalinichenko Jul 14 '17 at 07:18