Filter list with linq for similar items

20,987

It really depends on what you mean, by saying "similar"

Options:

1) var filteredItems = results.Where( p => p.Name != null && p.Name.ToUpper().Contains(queryString.ToUpper());

2) There is also also known algorithm as "Levenshtein distance":

http://en.wikipedia.org/wiki/Levenshtein_distance

http://www.codeproject.com/Articles/13525/Fast-memory-efficient-Levenshtein-algorithm

The last link contains the source code in c#. By using it you cann determine "how close" the query string to the string in your list.

Share:
20,987
Tester
Author by

Tester

Updated on October 28, 2020

Comments

  • Tester
    Tester over 3 years

    I have a list in which I filter, according to the text input in a TextBox in Xaml. The code below filters the List stored in the results variable. The code checks if the textbox input,ie, queryString, matches the Name of any item in the results list EXACTLY. This only brings back the items from the list where the string matches the Name of a the item exactly.

    var filteredItems = results.Where(
                    p => string.Equals(p.Name, queryString, StringComparison.OrdinalIgnoreCase));
    

    How do I change this so that it returns the items in the list whose Name, is similar to the queryString?

    To describe what I mean by Similar: An item in the list has a Name= Smirnoff Vodka. I want it so that if "vodka" or "smirnoff" is entered in the textbox, the the item Smirnoff Vodka will be returned.

    As it is with the code above, to get Smirnoff Vodka returned as a result, the exact Name "Smirnoff Vodka" would have to be entered in the textbox.

  • Tester
    Tester over 10 years
    You can see the edited question for a description on what I mean by similar.