问题描述
我有一个List<Unit>
,其中Unit
包含Name
和Value
.在此对象中,我存储有关服装尺码的信息,Name
包含尺码名称(S,M,L,XL ..),Value
包含该尺码的数量.
I have a List<Unit>
where Unit
contains Name
and Value
. In this object I store information about apparel sizes Name
contains size names (S,M,L,XL..) and Value
contains the quantity of that size.
此单元列表是从数据库中包含的,但是列表是随机排列的,因此在列表中,它可能是这样的:
This unit list is contained from a database, but the list comes in random order, so in the liste it might be like this:
Unit(M,3)
Unit(S,1)
Unit(XXL,2)
Unit(L,2)
我想对列表进行排序,使其变得更像这样:
I would like to sort the list so that it become more like this:
Unit(S,1)
Unit(M,3)
Unit(L,2)
Unit(XXLL,2)
我不能订购字符串ASCE
或DESC
,因为它M
在S
之前,依此类推.然后我想我可以创建一个具有正确顺序(XXS,XS,S,M,L,XL,XXL,XXXL)的引用数组,但是如何根据引用对列表进行排序.
I cant order on the string ASCE
or DESC
since it M
comes before S
and so on.Then I thought I might create an reference Array with the correct order (XXS,XS,S,M,L,XL,XXL,XXXL), but how can I sort my list according to the reference.
或者还有其他聪明的方法吗?
Or are there other clever ways of doing this?
更新
感谢所有好的回答,我找到了Enum
解决方案,它最终看起来像这样:
Thanks for all good answers, I landed on the Enum
solution, and it finally looks like this:
public class Unit
{
public Unit()
{
}
public Unit(string name, int value)
{
Value = value;
SizeCode = AssignSizeCode(name);
}
public SizeCode SizeCode { get; set; }
public int Value { get; set; }
private SizeCode AssignSizeCode(string name)
{
switch (name)
{
case "XXS":
return SizeCode.XXS;
case "XS":
return SizeCode.XS;
case "S":
return SizeCode.S;
case "M":
return SizeCode.M;
case "L":
return SizeCode.L;
case "XL":
return SizeCode.XL;
case "XXL":
return SizeCode.XXL;
case "XXXL":
return SizeCode.XXXL;
default:
return SizeCode.Unknown;
}
}
}
public enum SizeCode
{
XXS = 1,
XS = 2,
S = 3,
M = 4,
L = 5,
XL = 6,
XXL = 7,
XXXL = 8,
Unknown = 9
}
我这样排序:
units = units.OrderBy(x => (int)x.SizeCode).ToList();
有什么意见或我需要改进的地方吗?
Any comments, or things I can improve?
推荐答案
如何使用枚举
public enum Size
{
Small = 1,
Medium = 2,
// etc
}
然后,您可以将Unit类中的枚举值转换为int并按整数值排序.
Then you can convert the enum value in Unit class to int and sort by the integer value.
这篇关于按参考C#对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!