I am implementing a “Search” autocomplete. I’d like to return a list of results sorted by the ordering of the submitted characters by the user where items at the top of the sorted results are those items that have the characters in the string in the first to n characters.
Is there an elegant way to do this using LINQ?
For example, assume that when the user types “un” the following items are returned from the database.
- Texas, United States
- Florida, United States
- New York, United States
- United States
I would like to return the ordered result for display as follows:
- United States
- Texas, United States
- Florida, United States
- New York, United States
Notice that for each of the strings above “un” is in position 1-2, 7-8, 10-11 and 11-12.
Generally the answer from @HugoRune will work, but it’s a bit inefficient having two issues.
Using
ToLower()leads all strings to converted first to lowercase, even if the comparison of firts char shows that they do not match.We perform basically the same comparison two times. Once with
Contains()and once withIndexOf(). So we run through string two times.Following code is at least twice as efficient: