You can create a single routine that provides a name and a query string, and returns an integer value.
Once you do this, just go back in order:
int QueryOrder(string query, string name) { if (name == query) return -1; if (name.Contains(query)) return 0; return 1; }
Then do:
var results = userList.OrderBy(s => QueryOrder(query, s.Name));
The best part about this approach is that you could later expand the procedure to provide more detailed information that allows you to sort by the “good” match you get. For example, “Pete” → “Peter” is probably better than “Pete” → “Peter Smith,” so you could get your logic back for different options ...
If you need to remove non-Pete matches, you can also exclude the Where clause.
Reed copsey
source share