Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort strings so strings that start with a search term are at first?

Tags:

c#

sorting

search

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?

like image 220
Kyle Avatar asked Dec 18 '25 18:12

Kyle


2 Answers

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()
like image 54
Mike Zboray Avatar answered Dec 21 '25 07:12

Mike Zboray


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()
like image 35
McGarnagle Avatar answered Dec 21 '25 08:12

McGarnagle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!