I have a question for how to compare two strings.
here is the code.
string stringA = "This is a test item";
string stringB = "item test a is This";
Obviously, stringB contains every words from stringA, but in a different order.
My desired result should be TRUE.
My question is, what should I do? I have tried to use the .Contains() method, but the result is FALSE.
Thanks everyone.
UPDATES
Thanks everyone for the kindly replies.
Here is my clarification
I am actually building a database search function by using LINQ and EF.
Assume that, an item has its name as “This is a test item”.
If user input “test a is this”, I would like the function smart enough to catch the item mentioned above.
Any suggestion?
ANOTHER UPDATE
Thanks again for all your help.
I do like Peter Ritchie’s, codesparkle’s, Dave’s and EdFred’s suggestion.
Building on Peter Richie’s excellent suggestion, using
Array.Sort()instead ofList<T>.Sort(), without the duplication but packed into a neat extension method:Usage
Edit:
It’s hard to understand why you accepted an answer that does not comply with the requirements stated in your question.If you really want the strings"This is a test item"and"test a is this"to match, you’d need to use something a bit more involved, such as:You may want to come up with a better algorithm though, as this one is extremely loose — two identical words will be enough to count as a match. But this one will match your requirements as stated in the question.