Search code examples
c#stringliststartswith

C# - Ordering a list by the initial letters of its elements (StartsWith)


Consider a standard list. I need my list to be sorted in a manner that the first elements to be shown are the ones that StartsWith("SI_IS")

I asked one of my friends and he told me to use a lambda custom function, is this true?

The output should be something like

SI_ISFieldName
SI_ISbFieldName
SI_IScFieldName
F_FieldName
TB_FieldName
TB_bFieldName
...

Solution

  • You can use a conditional OrderBy, just remember that true is higher than false:

    var q = items.OrderByDescending(s => s.StartsWith("SI_IS"));
    

    or maybe you find this more readable:

    var q = items.OrderBy(s => s.StartsWith("SI_IS") ? 0 : 1);