2

I need to create a function that receives a list of strings, and returns a list of all the items that match (i.e., SQL "LIKE", case-insensitive and ignoring diacritics):

// Pseudocode example
IEnumerable<Item> Search(List<String> patterns)
{
    var result = new List<Item>();

    foreach (var Item in context.Items)
    {
        bool matches = true;

        foreach (var pattern in patterns)
        {
            if (!Item.Name.Contains(pattern))
            {
                matches = false;
                break;
            }
        }

        if (matches)
        {
            result.Add(Item);
        }
    }

    return result;
}

While something similar to this works, it's less than ideal (it seems horribly inefficient).

Is it possible to create a (possibly LINQ) query that generates something similar to the following SQL?:

SELECT *
FROM items
WHERE items.name LIKE :pattern1
  AND items.name LIKE :pattern2
  ...
  AND items.name LIKE :patternN

1 Answer 1

3

You can simply iterate your patterns and apply a WHERE clause for each.

var patterns = new List<string>();
using (var context = new MyDataContext())
{
    var query = (IQueryable<Area>)context.Areas;

    foreach (var pattern in patterns)
    {
        query = query.Where(a => a.Description.Contains(pattern));
    }

    return query.ToList();
}

As you probably know, the query is lazy-executed, and in this case won't be executed until the ToList call after all patterns are applied.

Sign up to request clarification or add additional context in comments.

2 Comments

What about the other part of the question? Would Contains handle diacritics, or is there a method that will?
@Tordek You can specify a case-insensitive match with StringComparer.CurrentCultureIgnoreCase, but I don't know about diacritics. To be honest I'd not expect that they can be handled easily and you may need a mapping pattern to map (for example) an á to an a.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.