LINQ to SQL query filter, with the name match ignoring multiple punctuation characters I have the following LINQ to SQL query which works fine but looks ugly:

var filter = "filter";

query = query.Where(x =&gt;
    x.Name.Replace("'", "").Replace("\"", "").Replace("#", "").Replace("/", "").Replace("-", "").Contains(filter) ||
    x.FullName.Replace("'", "").Replace("\"", "").Replace("#", "").Replace("/", "").Replace("-", "").Contains(filter));


It'd be nice to be able to do something similar to this (which isn't possible because LINQ to Entities won't recognize the method):


var filter = "filter";
var removals = new string[] { "'", "\"", "#", "/", "-" };

query = query.Where(x =&gt;
  Replaces(x.Name, removals).Contains(filter) ||
  Replaces(x.Full, removals).Contains(filter));



... but I can't figure out how that could be written. I've written predicates that dealt with entire expressions, but not with just a single property.

This is a LINQ to SQL expression, so I can't just pull it out into its own method or I'll get an error like:


  Additional information: LINQ to Entities does not recognize the method
  'System.String RemoveAll
You are rather removing those parts instead of replacing them, so more appropriate name would be remove all.

You can make your own extension method like this : 

public static class Extensions
{
    public static string RemoveAll(this string source, string[] charsToRemove)
    {
        return charsToRemove.Aggregate(source, (current, t) =&gt; current.Replace(t, string.Empty));
    }
}


If you really want to replace them with something you can do it like this :

public static string ReplaceAll(this string source, string[] charsToRemove, string[] charsToReplace)
{
    string result = source;
    for (var i = 0; i &lt; charsToRemove.Length; i++)
    {
        result = result.Replace(charsToRemove[i], charsToReplace[i]);
    }
    return result;
}


Example usage : 

var filter = "filter";
string[] itemsToRemove = {"'", @"""",};

query = query.Where(x =&gt;
    x.Name.RemoveAll(itemsToRemove).Contains(filter) ||
    x.FullName.RemoveAll(itemsToRemove).Contains(filter));


UPDATE

LINQ to SQL would require you to call .AsEnumerable(), .ToList() or .ToArray() first before operating on strings, you might loose some performance from that but the other way is to write your custom query provider or stick with what you have.