Search string in array of strings in 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 an exception

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

How can I match a char with a string?

+6
source share
2 answers

Instead, you can use s.Surname.First() :

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

This is because Linq to Entities does not know what to do with char.ToString()

Since you are dealing with List<string> , you can use:

 filter.And(s => initials.Any(x => x.Contains(s.Surname.First())); 
+8
source

The following code solved my problem -

  var initials = Queries["SurnameInitial"].Split(',').ToList(); filter.And(s => initials.Contains(s.Surname.Substring(0, 1))); 
+2
source

Source: https://habr.com/ru/post/1013328/


All Articles