Search code examples
c#sqlasp.net-coreentity-framework-corecontains

Using 'Contains' in linq query


Consider the below query:

  public async Task<IEnumerable<string>> GetItemNo(string itemNumber)
    {
        return await itemDbContext.Item
                     .Where(p => p.ItemNo.Contains(itemNumber)) 
                     .Select(p => p.ItemNo).ToListAsync();

    }

Instead of checking passed in characters exist in the same order (Which is how '.Contains' works right now).

How do I return list of ItemNos (string), even if few characters match and even if characters match in different place.

For eg: If I pass in "appl" or "apole" or "dpple". I want DB to list "apple". Thank you.


Solution

  • You need to use a metric that tells you if your string match is "good enough". One such metric is the Levenshtein distance. You can calculate the distances between the input string and all the strings in your collection and then select those entries from the collection which have a distance that is low enough.