I suggest mapping (i.e. map actual city name to the desired order):
Dictionary<string, int> order = new Dictionary<string, int> {
{"Lahore", 1},
{"Islamabad", 2},
{"Karachi", 3},
};
...
var result = myCollection
.OrderBy(city => order[city]);
In case you have arbitrary cities in the myCollection
and want first have Lahore
, Islamabad
, Karachi
(in this order) and then all the other cities:
var result = myCollection
.OrderBy(city => order.TryGetValue(item, out var map) ? map : int.MaxValue)
.ThenBy(city => city);
Edit: Why Dictionary
? Dictionary is efficient in general case, esp. if you have a long list of cities. To turn a list into the dictionary:
List<string> cities = new List<string>() {
"Lahore",
"Islamabad",
"Karachi",
};
Dictionary<string, int> order = cities
.Select((value, index) => new {value = value, index = index})
.ToDictionary(item => item.value, item => item.index);
However, If you have a guarantee that it'll be just few (say, 3
) exceptional cities my solution is an overkill and Tim Schmelter's one is better.