开发者

Searchstrings with Linq?

Hi,

I need to let the enduser type search strings like :

Volvo S70 OR S60 > All posts that contins Volvo OR S70 OR S60

Volvo S70 NOT S60 > All posts that contains Volvo and S70 but not S60

"Volvo S70" > All posts that includes "Volvo S70" as one string

Volvo S* > All posts that contains Volvo and a word starting with S

"Volvo S70" "Volvo S60" V* > All posts that contains "Volvo S70" or "Volvo S60" Or a word starting on V

Vo*l* S* > * is treated as wildcards so in this case posts that contains Vo*l* or S*

This is just a small part off possible combinations.

How do I handle this with Linq to Object?

I Know that I can use StartsWith, EndsWith, Contains but this will mean that I have to split the incoming search string, is this the only way? And how do I then handle strings like Vo*l*?

BestRegards

Edit1: The data hav开发者_JS百科e been fetched from database with entityframework, this means that the data is now in application (List)


If you want to unleash the full power of text search you can use Lucene.NET . It's not too easy to set up but it gives you a lot of power with full text searches and indexing. It can also be set up to work with LinqToEntities.

http://linqtolucene.codeplex.com/


Since the data is already there and there's nothing in place in .NET to handle complex search strings with LINQ, I wonder if creating your own Query Extension Method would be too far in right field?

I'm thinking your best bet is to write your own parser which converts your search rules into regular expressions. Your syntax may be too complicated for the simple LIKE functionality and indexed search is not an option unless you take the time to use Lucene, which I don't know much about.

This parser can then be called from a Query Extension Method to filter your data or find it.


If StartsWith, EndsWith, Contains isn't good enough for you. You can use this function

public ObjectQuery<T> Where( string predicate, params ObjectParameter[] parameters )

Like this (you can use any sql operator):

ObjectQuery<Product> productQuery2 = productQuery1.Where("it.ProductID = @productID")


My solution is to use ESQL like this :

using (Entities context = new Entities())
      {
IQueryable<Ad> ads = context.CreateQuery<Ad>("SELECT VALUE C FROM Ads AS C WHERE C.Title LIKE @searchS OR C.Description LIKE @searchS", new ObjectParameter("searchS", searchS));

            ads = ads.Where(c => c.InactivatedDate.HasValue == inactive);
            ads = ads.Where(c => c.PublishedDate.HasValue && c.PublishedDate.Value.CompareTo(fetchAdsTo.Value) >= 1);

            output = ads.ToList();
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜