Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list of strings by placing words starting with a certain letter at the start

Tags:

c#

list

linq

Assuming I have the following list:

IList<string> list = new List<string>();
list.Add("Mouse");
list.Add("Dinner");
list.Add("House");
list.Add("Out");
list.Add("Phone");
list.Add("Hat");
list.Add("Ounce");

Using LINQ how would I select the words containing "ou" and sort the selection such that the words beginning with "ou" are listed at the start and then the words containing but not starting with "ou" are subsequently listed. The list I'm trying to create would be:

Ounce
Out
House
Mouse

I came up with the following but it is not working:

list.Where(x => x.Contains("ou"))
    .OrderBy(x => x.StartsWith("ou"))
    .Select(x => x);
like image 604
Peadar Doyle Avatar asked Feb 20 '23 13:02

Peadar Doyle


1 Answers

You're getting a case-sensitive comparison, and also you need OrderByDescending(). A quick and dirty way to achieve the case-insensitivity is ToLowerInvariant():

var result = list.Where(x => x.ToLowerInvariant().Contains("ou"))
                    .OrderByDescending(x => x.ToLowerInvariant().StartsWith("ou"))
                    .Select(x => x);

Live example: http://rextester.com/GUR97180

This previous answer shows the correct way to do a case insensitive comparison (ie, dont use my example above, its bad)

like image 140
Jamiec Avatar answered May 10 '23 20:05

Jamiec