Reputation: 15190
I want to order by my results with the matches count in my string line.
So here is code
.ThenByDescending(p => p.Title.ToLower()
.Split(' ')
.Count(w => words.Any(w.Contains)));
But it bring me error and says that LINQ can't parse Split
into SQL.
LINQ to Entities does not recognize the method 'System.String[] Split(Char[])' method, and this method cannot be translated into a store expression.
How can I implement Split via LINQ?
For example, for this array it must order in this way
words = { "a", "ab" }
ab a ggaaag gh //3 matches
ba ab ggt //2 matches
dd //0 matches
Upvotes: 6
Views: 7137
Reputation: 52788
You will need to perform the sorting in LINQ to Objects because LINQ to Entities cannot translate the C# code into SQL (or the language of whatever DB you're using).
You can do it like this.
var results =
objectContext
.Where(a => a == b) //Whatever
.AsEnumerable()
.ThenByDescending(p=>p.Title.ToLower().Split(' ').Count(w=>words.Any(w.Contains)));
AsEnumerable()
(along with ToArray()
or ToList()
) turn the LINQ to Entities back into LINQ to Objects.
Upvotes: 3
Reputation: 113402
One can't expect LINQ to Entities to be able to convert that to SQL.
The best solution is to change the schema such that each word in a post's title is stored as a separate row in a separate table (with the appropriate associations). The query can then use explicit (group) join operations or the FK association property.
If you can't do this and yet want the query to run on the database, you'll have to look into writing a user-defined function to work with delimited strings. Read this question for more info. This will be a lot of work though.
The easiest solution (if you can afford to do it) of course is to pull everything back to the client just use LINQ to Objects for that part of the query, as mentioned by @Muhammad Adeel Zahid.
Upvotes: 2
Reputation: 17784
it means that Linq to entities failed to find translation of split method that can be written as sql query. if you want to perform split functions you have to bring the record in memory by calling ToList()
, AsEnumerable()
etc.
var result = (from t in db.Table
select t).AsEnumerable().OrderBy(x=>x.Column).ThenByDescending(p=>p.Title.ToLower.Split(' ')....);
Upvotes: 8