List complex sorting

Create an array of sizes in the order you want them to be in, then sort the shirts by the position of their sizes in that array:

string[] sizes = new [] {"XS", "S", "M", "L", "XL", "XXL", "UK 10", "UK 12"};

var shirtsInOrder = shirts
                        .OrderBy(s=>sizes.Contains(s) ? "0" : "1")  // put unmatched sizes at the end
                        .ThenBy(s=>Array.IndexOf(sizes,s))  // sort matches by size
                        .ThenBy(s=>s); // sort rest A-Z

Leave a Comment