0

Let's say I have these items in a list full of strings:

  • Cash
  • Cheque
  • Postal Order
  • Credit Card
  • Bank Transfer
  • etc... etc... etc...

I found a nice thing called "LevenshteinDistance". This is working up to some point. It does not always return the correct string if I type something wrong.

I am thinking of going to the Regex side to get this.

Basically I want to type, for example, "chq" and it should return "Cheque".

I have this code to try this but it is also not working correctly:

foreach (string entry in lsbSuppliedData.Items)
{
    entr = entry.Trim().Replace(" ", "");
    regex = new Regex("^[" + inputString + "]+$", RegexOptions.IgnoreCase);

    if (regex.IsMatch(inputString))
    {
        proposal = entry;
        //break;
    }
}

Can someone please just help me into the right direction? I have a list with the items it should suggest, which at max would be 20 items (not very big, so performance is not a big issue).

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
Fred
  • 2,402
  • 4
  • 31
  • 58

1 Answers1

3

You can try this:

var words = new[] { "Cash", "Cheque" ... };

string search = "chq";

var results = words
             .Where(x => x.ToLower()
                        .Intersect(search.ToLower().Distinct()).Count() >= search.Length);

This would work and ignore the case sensitivity and also the order of letters for ex if you type cqh it will still return Cheque, if you don't want this to happen, it requires much more work.Also you can change Where to First or FirstOrDefault if you want to get a single result instead of all matches.

Update: Here is another version that doesn't ignore the order of letters:

var result = words
            .FirstOrDefault(x => x.ToLower().Where(search.Contains).SequenceEqual(search));
Selman Genç
  • 100,147
  • 13
  • 119
  • 184