List <class> in alphabetical order, keeping certain elements at the top?

I have a List<StreetSuffix> that I would like to order in alphabetical order, keeping the most used at the top.

My class is as follows:

 public class StreetSuffix { public StreetSuffix(string suffix, string abbreviation, string abbreviation2 = null) { this.Suffix = suffix; this.Abbreviation = abbreviation; this.Abbreviation2 = abbreviation2; } public string Suffix { get; set; } public string Abbreviation { get; set; } public string Abbreviation2 { get; set; } } 

I know that I can order my list using:

 Suffix.OrderBy(x => x.Suffix) 

This list will be used to feed combobox , from the elements in the list that I would like to save at the top of the following suffix in the same order:

 Road Street Way Avenue 

Is there a way to do this using LINQ or do I need to intervene for these specific entries?

+4
source share
2 answers

You can do it:

 // Note: reverse order var fixedOrder = new[] { "Avenue", "Way", "Street", "Road" }; Suffix.OrderByDescending(x => Array.IndexOf(fixedOrder, x.Suffix)) .ThenBy(x => x.Suffix); 
+4
source

Use OrderBy .. (priority order) ThenBy .. (secondary order)

Or by implementing IComparer and use this with OrderBy. The primary order will be an external condition.

+1
source

Source: https://habr.com/ru/post/1488807/


All Articles