简体   繁体   中英

List<class> alphabetical order while keeping certain items at the top?

I have a List<StreetSuffix> that I would like to order alphabetically while maintaining the most used at the top.

My class Looks like this:

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 I can order my list using:

Suffix.OrderBy(x => x.Suffix)

This list will be used to fed a combobox , from the items on the list I would like to keep at the top the following suffix on the same order:

Road
Street
Way
Avenue

Is there a way to do this using LINQ or do I have to intervent myself for this specific entries ?

You could do this:

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

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

Or, implement a custom IComparer and use that with OrderBy. The primary ordering will be the outside conditional.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM