Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search string within a string array in a LINQ expression

if (!string.IsNullOrEmpty(Queries["SurnameInitial"]))
{
    var initials = Queries["SurnameInitial"].Split(',').ToList();
        filter.And(s => initials.Contains(s.Surname.ToArray()[0].ToString()));
}

It throws exception

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

How can i match char vs string?

like image 480
s.k.paul Avatar asked Dec 20 '16 10:12

s.k.paul


2 Answers

You can use the following s.Surname.First() instead:

if (!string.IsNullOrEmpty(Queries["SurnameInitial"]))
{
    var initials = Queries["SurnameInitial"].Split(',');
        filter.And(s => initials.Contains(s.Surname.First()));
}

This happens because Linq to Entities doesn't know what to do with char.ToString()

Since you're dealing with a List<string> you can use:

filter.And(s => initials.Any(x => x.Contains(s.Surname.First()));
like image 95
Thomas Ayoub Avatar answered Nov 14 '22 23:11

Thomas Ayoub


The following code solved my problem-

 var initials = Queries["SurnameInitial"].Split(',').ToList();
 filter.And(s => initials.Contains(s.Surname.Substring(0, 1)));
like image 40
s.k.paul Avatar answered Nov 14 '22 22:11

s.k.paul