Reputation: 53
I need a linq/lambda expression that sorts a list of strings but only the first 2 letters. Uppercase letters should be sorted first.
MyList.Sort((s1, s2) =>
s1.Substring(0, 2).CompareTo(
s2.Substring(0, 2)));
This is what i have now. It succesfully sorts the first 2 letters but when its case sensitive it fails...
EDIT: This is the result and works:
var sorted = MyList.OrderBy(x =>x[0]).ThenBy(x => x[1]).ToList();
Upvotes: 2
Views: 1471
Reputation: 29016
Why not a simple OrderBy()
and .ThenBy
as they performs a case sensitive comparison for sorting, consider the following code:
List<string> unOrderedList = new List<string>() { "bAC", "ABC", "aBc", "abc", "cAb", "Abx", "bbc", "bBx", "cAA" };
var orderedList = unOrderedList.OrderBy(x => x[0]).ThenBy(y=>y[1]).ToList();
Here in this case the orderedList
will have the output as:
ABC
Abx
aBc
abc
bAC
bBx
bbc
cAb
cAA
See the example here, You can see that Abx
have a higher position in the List than aBc
, You can see a similar case in bBx
and bbc
.
Upvotes: 7