Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 954
youngseagul Avatar asked Dec 12 '22 01:12

youngseagul


2 Answers

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.

like image 149
juharr Avatar answered Jan 18 '23 06:01

juharr


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();
like image 21
EZI Avatar answered Jan 18 '23 07:01

EZI