Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a C# list by word

I want to sort a C# list by word. Assume I have a C# list (of objects) which contains following words:

[{id:1, name: "ABC"},
 {id:2, name: "XXX"},
 {id:3, name: "Mille"},
 {id:4, name: "YYY"},
 {id:5, name: "Mill",
 {id:6, name: "Millen"},
 {id:7, name: "OOO"},
 {id:8, name: "GGGG"},
 {id:9, name: null},
 {id:10, name: "XXX"},
 {id:11, name: "mil"}]  

If user pass Mil as a search key, I want to return all the words starting with the search key & then all the words which does not match criteria & have them sort alphabetically.

Easiest way I can think of is to run a for loop over the result set, put all the words starting with search key into one list and put the renaming words into another list. Sort the second list and them combine both the list to return the result.

I wonder if there is a smarter or inbuilt way to get the desired result.

like image 292
SharpCoder Avatar asked Jun 30 '16 21:06

SharpCoder


People also ask

What is sort () in C?

sort is a generic function in the C++ Standard Library for doing comparison sorting. The function originated in the Standard Template Library (STL).

What is sort () and give example?

Sorting is the process of placing elements from a collection in some kind of order. For example, a list of words could be sorted alphabetically or by length. A list of cities could be sorted by population, by area, or by zip code.

Is there a sorting library in C?

Standard C library provides qsort function that can be used for sorting an array. Following is the prototype of qsort() function. // Sort an array of any type.


1 Answers

Sure! You will sort by the presence of a match, then by the name, like this:

var results = objects.OrderByDescending(o => o.Name.StartsWith(searchKey))
                     .ThenBy(o => o.Name);

Note that false comes before true in a sort, so you'll need to use OrderByDescending.

As AlexD points out, the name can be null. You'll have to decide how you want to treat this. The easiest way would be to use o.Name?.StartsWith(searchKey) ?? false, but you'll have to decide based on your needs. Also, not all Linq scenarios support null propagation (Linq To Entities comes to mind).

like image 138
Daniel Avatar answered Sep 23 '22 14:09

Daniel