列表<字符串>复杂排序 [英] List<string> complex sorting
问题描述
我有一个List
尺码,比如XS、S、M、L、XL、XXL、UK 10、UK 12等
I have a List<string>
of sizes, say XS, S, M, L, XL, XXL, UK 10, UK 12 etc
我想要的是强制顺序为上面的顺序,无论列表中项目的顺序如何,我想我需要一个 IComparable 运算符但不确定.
What I want is to force the order to be that of above, regardless of the order of items in the list, I think I need a IComparable operator but unsure.
理想情况下,我想要另一个具有正确顺序的列表,它可以引用它在列表中的位置"并重新排序,如果它不存在,它将默认为 A-Z
Ideally I want to have another List with the correct order in which it can reference it's 'place' in the list and re-sort itself, if it doesn't exist it will default to A-Z
推荐答案
按照您希望的尺寸顺序创建一个尺寸数组,然后根据衬衫尺寸在该数组中的位置对衬衫进行排序:
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
这篇关于列表<字符串>复杂排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!