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)
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?
Update
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
}
And I sort it like this:
units = units.OrderBy(x => (int)x.SizeCode).ToList();
Any comments, or things I can improve?
How about using a enum
Then you can convert the enum value in Unit class to int and sort by the integer value.