清单&LT;串GT;复杂的分类 [英] List<string> complex sorting
问题描述
我有一个列表&LT;串&GT;
尺寸,说XS,S,M,L,XL,XXL,英国10,英国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
这篇关于清单&LT;串GT;复杂的分类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!