Split string with LINQ

和自甴很熟 提交于 2019-12-10 15:23:11

问题


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

回答1:


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(' ')....);



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/8653200/split-string-with-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!