youngseagul
youngseagul

Reputation: 347

Order by names starting by searched string alphabetically LINQ

I have following data

jabb
Bucynski
Bartley
Abart
Benson
Brown
Beerbower
Mack
Nina
Salt
Walter

User performs search on these records, I want to sort records in such a way that records starting with search string should appear on top in alphabetical order and the remaining records should come after those. Suppose user searches “b” then search result list should be like this

Bartley
Beerbower
Benson
Brown
Bucynski
Abart
jabb
Mack
Nina
Salt
Walter

We see two groups here, one is starting with “b” in alphabetical order and all else down in alphabetical order

Note : I have tried like this

IEnumerable<Admin_Customer_List_Result> adminResult;

adminResult adminResult.OrderBy(m => m.Last_Name.StartsWith(searchString) ? 0 : 1)

Upvotes: 4

Views: 4180

Answers (2)

juharr
juharr

Reputation: 32296

Just add a ThenBy after that to order the stuff that starts with b and the stuff that doesn't. Also you might need to do a case insensitive comparison if you want a lower case "b" to match the names that start with an upper case "B".

adminResult.OrderBy(m => m.Last_Name.ToLower()
                          .StartsWith(searchString.ToLower()) ? 0 : 1)
           .ThenBy(m => m.Last_Name);

Additionally you can use OrderByDescending and you won't need the ? 0 : 1.

Upvotes: 14

EZI
EZI

Reputation: 15364

var list = new List<string> { "Jabb", "Bucynski", "Bartley", "Abart", "Benson", "Brown", "Beerbower", "Mack", "Nina", "Salt", "Walter" };
string input = "B";
var result = list.GroupBy(x => x.StartsWith(input))
                 .OrderByDescending(x => x.Key) //order groups
                 .SelectMany(g => g.OrderBy(x => x)) //order items in each group
                 .ToList();

Upvotes: 2

Related Questions