0

Here is my code:

string[] customerNames = searchModel.CustomerName.Split(',');
 query = query.Where(d => customerNames.Contains(d.CustomerName, comparer) || customerNames.Contains(d.Company1.CompanyName, comparer));

Which works if you are just looking for exact matches. However I'd like to partial match, ie: if customerNames contains an element 'ell', it would select d if d.CustomerName was 'Hello' since 'ell' is in 'Hello'

I tried overriding the EqualityComparer, but I believe it is trying to use the GetHashCode function rather than the Equals in the Comparer, which I'm not sure how to implement.

How should I go about this?

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
Dave
  • 1,645
  • 2
  • 23
  • 39
  • Similar question: http://stackoverflow.com/questions/3748289/linq2sql-like-command-for-phrase – Rudis Feb 10 '14 at 22:51
  • GetHashCode is not guaranteed to prevent collisions so you can be sure there's more going on than that. – Casey Feb 10 '14 at 22:55

1 Answers1

1
string[] customerNames = searchModel.CustomerName.Split(',');
query = query.Where(d => customerNames.Any(c => c.Contains(d.CustomerName)) || customerNames.Any(c => c.Contains(d.Company1.CompanyName)));

But you should be aware, that it may get really slow when customerNames has a lot of items.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • I just was answering this myself. I'll check you off when 8 minutes has passed. customerNames should be very few items, but yeah I'm not sure what I can do to avoid this logic. – Dave Feb 10 '14 at 22:55
  • Will it translated to sql or will executed on client side on full set? – Hamlet Hakobyan Feb 10 '14 at 22:56
  • You can use [`PredicateBuilder`](http://www.albahari.com/nutshell/predicatebuilder.aspx) and just add list of `OR` conditions to your query. Which should probably be better and faster then `Any`+`Contains` chain. – MarcinJuraszek Feb 10 '14 at 22:56
  • @HamletHakobyan Should be transform into SQL (that's why I removed the comparer). – MarcinJuraszek Feb 10 '14 at 22:57
  • The expression tree would be better solution in this case. – Hamlet Hakobyan Feb 10 '14 at 22:59
  • Marcin- it should actually be c => d.CustomerName.Contains(c) I believe. Might not of been obvious from how I worded the question however. – Dave Feb 10 '14 at 23:03