Search code examples
c#listsortingalphabetical

Alphabetize list by using last 3 characters with C#?


I have a list of strings like this:

  1. 123.45 ABC
  2. 678.90 DEF
  3. 543.21 FED

I want to sort the list alphabetically using the last 3 characters of each list element.

EDIT: Using C#, how do I alphabetize this list by using the last 3 characters of each element?


Solution

  • What I would first do is to ensure that I filter out all strings that have less than 3 characters. Then I would order them as:

    var items = new List<string> { "13 zzz", "12 yyy", "11 zzz" };
    
    items = items.Where(i => i.Length > 2)
                 .OrderBy(i => i.Substring(i.Length - 3))
                 .ToList();