Johan
Johan

Reputation: 35223

Wildcard search in using Lambda in EF

I have a search with optional arguments:

string id1 = HttpContext.Current.Request["id1"];
string id2 = HttpContext.Current.Request["id2"];

List<Foo> list = context.Foo.Where(l => 
     (string.IsNullOrEmpty(id1) || l.Id1.Contains(id1)) &&
     (string.IsNullOrEmpty(id2) || l.Id2.Contains(id2)))
     .Take(10)
     .ToList());

I would like to extend it so that if the string starts with a *, the EndsWith() - method should be used.

For example, if the first searchstring is *123, I want to do a l.Id1.EndsWith("123").

Is there any way to extend my current code, or should I use a different approach?

Upvotes: 0

Views: 2072

Answers (1)

Dustin Kingen
Dustin Kingen

Reputation: 21275

I'm quite sure if this is what you were intending, but you can break your logic up by using IQueryable(T). The query won't be executed until you try to use the collection.

public IList<Foo> Search(DbContext<Foo> context, string id1, string id2)
{
    Func<Foo, bool> predicate = l =>
            (string.IsNullOrEmpty(id1) || l.Id1.Contains(id1))
            && (string.IsNullOrEmpty(id2) || l.Id2.Contains(id2)));

    IQueryable<Foo> list = context.Foo.Where(predicate);

    if(id1.StartsWith("*") && id1.Length > 1)
    {
        var searchTerm = id1.Substring(1, id1.Length);
        list = list.Where(l => l.EndsWith(searchTerm));
    }

    return list.Take(10).ToList(); // Execution occurs at this point
}

Building up the query:

public void BasicSearch(IQueryable<foo> list, string id1, string id2)
{
    Func<Foo, bool> predicate = l =>
            (string.IsNullOrEmpty(id1) || l.Id1.Contains(id1))
            && (string.IsNullOrEmpty(id2) || l.Id2.Contains(id2)));

    list.Where(predicate);
}

public void WildcardSearch(IQueryable<Foo> list, string id1)
{
    if(!id1.StartsWith("*") || id1.Length <= 1) return;

    var searchTerm = id1.Substring(1, id1.Length);
    list.Where(l => l.EndsWith(searchTerm));
}

IQueryable<Foo> list = context.Foo;

BasicSearch(list, id1, id2);
WildcardSearch(list, id1);
var result = list.Take(10); // Execution occurs at this point

Upvotes: 1

Related Questions