How to efficiently limit and then concatenate a result with a linq / lambda expression?

c#, concatenation, lambda

Solution

It might be more efficient as a two-step ordering:

var results = records.OrderBy(r => r.Name.StartsWith(term) ? 1 : 2)
                     .ThenBy(r => r.Name)
                     .Take(MaxResultSize);

Problem

I am in the process of creating a service to make it easy for a user to select a protocol from the IANA - Protocol Registry. As you might imagine searching the registry for the term `http` pulls up a lot of hits. Since `amt-soap-http` is going to selected by a user much less frequently than straight `http` I decided that it would be a good idea to pull out everything that starts with `http` and then concatenate that with the remaining results. The below lambda expression is the result of that thought process: ``` var records = this._ianaRegistryService.GetAllLike(term).ToList(); var results = records.Where(r => r.Name.StartsWith(term)) .OrderBy(r => r.Name) .Concat(records.Where(r => !r.Name.StartsWith(term)) .OrderBy(r => r.Name)) .Take(MaxResultSize); ``` Unfortunately, I feel like I am iterating through my results more times than necessary. Premature optimization considerations aside is there a combination of lambda expressions that would be more efficient than the above?

Original source