Home > Software engineering >  How to compare list of strings to a string where elements in the list might have letters be scramble
How to compare list of strings to a string where elements in the list might have letters be scramble

Time:01-02

I'm trying to write a lambda expression to compare members of a list to a string, but I also need to catch elements in the list that might have their letter scrambled up.

Here's code I got right now

List<string> listOfWords = new List<String>() { "abc", "test", "teest", "tset"};
var word = "test";
        
var results = listOfWords.Where(s => s == word);

foreach (var i in results)
    {
      Console.Write(i);
    }

So this code will find string "test" in the list and will print it out, but I also want it to catch cases like "tset". Is this possible to do easily with linq or do I have to use loops?

CodePudding user response:

How about sorting the letters and seeing if the resulting sorted sequences of chars are equal?

var wordSorted = word.OrderBy(c=>c);
listOfWords.Where(w => w.OrderBy(c=>c).SequenceEqual(wordSorted));
  • Related