简体   繁体   中英

Find values where a word is repeated

Is there a way in LINQ to Entities (SQL) to identify all records where a specified word is repeated at least/less than a specified number of times?

I can do this in memory, looking for at least 3 instances of the word "word" using:

Where(Function(x) x.Description.Split("word").Count > 3)

However the Split() function cannot translate to a SQL equivalent, and so this can only be executed in-memory, which is excruciatingly slow by the time any number of records are involved.

The SQL to do this would be something like

WHERE Description LIKE '%word%word%word%'

And that's as far as I get - I can't work out how to get that SQL generated by LINQ to Entities. I tried the ugly hacky .Where(Function(x) x.Description.Contains("word%word%word") on the off chance, but I'm almost relieved that it doesn't work!

Linq2SQL

.Where (c => SqlMethods.Like(c.name, "word%word%word"));

Linq2Entities
See: http://jendaperl.blogspot.com/2011/02/like-in-linq-to-entities.html
and http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/6529a35b-6629-44fb-8ea4-3a44d232d6b9/

.Where("it.Name LIKE @searchTerm", 
    new ObjectParameter("searchTerm", "word%word%word")); 

Try this:

.Where (x => SqlMethods.Like(x.Description, "word%word%word"));

From here: http://blogs.microsoft.co.il/blogs/bursteg/archive/2007/10/16/linq-to-sql-like-operator.aspx

Well it seems there is no way to express the required LIKE clause in LINQ to Entity... But what about using some other logic to detect "3 words" in the string.. something like:

Where(s => s.Description.Replace(" ", "").Replace("word", "").Length == s.Description.Replace(" ", "").Length - ("word".Length * 3) )

This is completely turned into SQL.

You can use Regular expression for that:

.Where(Regex.Match(".+word.+word.+word.+",x.Description)

I'm not quite sure about syntax, but i think you get the idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM