Contains method for compare string array in C#

Saeed Hamed picture Saeed Hamed · Aug 14, 2013 · Viewed 7.2k times · Source

I want to compare a sting field with a string array using LINQ, I’ve written the below extension method for comparing but it doesn’t work correctly.

 public static bool Contains(this string source, string[] keys)
    {
        foreach (var item in keys)
        {
            if (source.Contains(item))
                return true;
        }

        return false;
    }

And this is my query:

string[] keys = key.Split('+');
        var pages = context.Pages.Where(x => x.Title.Contains(keys));

The error that I’ve got is:

LINQ to Entities does not recognize the method 'Boolean Contains(System.String, System.String[])' method, and this method cannot be translated into a store expression.

Answer

Jon Skeet picture Jon Skeet · Aug 14, 2013

You can't use your own custom methods within LINQ like this - but you may be able to get away with rewriting it using the normal LINQ operators:

string[] keys = key.Split('+');
var pages = context.Pages.Where(x => keys.Any(key => x.Title.Contains(key)));

If that doesn't work, I suspect it's basically infeasible in EF.