Sarahrb
Sarahrb

Reputation: 669

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.

Upvotes: 0

Views: 1279

Answers (2)

radoslawik
radoslawik

Reputation: 1202

You could write a function that compares those two strings bool IsMatch(string a, string b); and use it in the Where query

.Where(p => IsMatch(p.ItemNo, itemNumber) == true)

Upvotes: 0

Xaver
Xaver

Reputation: 1041

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.

Upvotes: 1

Related Questions