开发者

Search facility like CONTAINS or FREETEXT using Linq

I'm hoping that the title of this is pretty straight forward enough. Basically, I have a database which doesn't have the Full-text indexing installed. Rather开发者_开发问答 than installing the Full-text indexing, I was wondering if there is a way of doing this with Linq?


You can write LINQ queries that use instance methods on System.String. Most LINQ providers are able to convert this to SQL statements. For instance:

from customer in db.Customers
where customer.Name.Contains("foo") || customer.Name.Contains("bar")
select customer;

LINQ to Entities will convert this to something like this:

SELECT T1.*
FROM Customers T1
WHERE T1.Name LIKE '%' + @p1 + '%'
OR T1.Name LIKE '%' + @p2 + '%'

Note that when you need a dynamic number of words to search for, you can use the PredicateBuilder. It allows you to build predicates that contain OR statements. Rewriting it with unions is also an effective method. For instance:

string[] searchWords;

// Define an empty set.
var customers =
    from customer in db.Customers
    where false
    select customer;

// Union the empty set with a set for a word.
foreach (var temp in searchWords)
{
    var searchWord = temp;

    customers = customers.Union(
        from customer in db.Customer
        where customer.Name.Contains(searchWord)
        select customer);
}


I believe you are after something like:

from xx in table
where uids.Contains( xx.uid.ToString() )
select xx

?

If you are after seperate string searching, perhaps:

string input = "some String";
string[] toSearchFor = GetSearchStrings();
var containsAll = toSearchFor.All(x => input.Contains(x));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜