I have a big list of strings. I am currently handling a search by doing a
.Where(x => x.Contains(search)).ToArray()
This gets all of the results I want, but in a poor order. For example a search for "ch" could come up with:
Potato Starch
Chicken
Since they both contain ch, I want them to both show up, but I want Chicken to be first in the array since it starts with ch.
What are some ways I could go about reordering my results so strings that start with the search string are at the start of the array?
You can order by the index, thus having strings starting with the search at the beginning:
.Where(x => x.Contains(search)).OrderBy(x => x.IndexOf(search)).ToArray()
You can add a simple OrderBy field that places the relevant results at the top:
.Where(x => x.Contains(search))
.OrderBy(x => x.StartsWith(search) ? 0 : 1)
.ThenBy(x => x)
.ToArray()
Note that if this is a database query (Linq to SQL/entities), you'll need to enumerate the results first, as the engine won't know how to translate it to SQL:
.Where(x => x.Contains(search))
.AsEnumerable()
.OrderBy(x => x.StartsWith(search) ? 0 : 1)
.ThenBy(x => x)
.ToArray()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With