List complex sorting

后端 未结 5 1315
攒了一身酷
攒了一身酷 2020-11-27 07:37

I have a List of sizes, say XS, S, M, L, XL, XXL, UK 10, UK 12 etc

What I want is to force the order to be that of above, regardless of th

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 08:38

    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
    

提交回复
热议问题