Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort strings by a different value

Tags:

c#

sorting

I've tried looking for an existing question but wasn't sure how to phrase this and this retrieved no results anywhere :(

Anyway, I have a class of "Order Items" that has different properties. These order items are for clothing, so they will have a size (string).

Because I am OCD about these sorts of things, I would like to have the elements sorted not by the sizes as alphanumeric values, but by the sizes in a custom order.

I would also like to not have this custom order hard-coded if possible.

To break it down, if I have a list of these order items with a size in each one, like so:

2XL
S
5XL
M

With alphanumeric sorting it would be in this order:

2XL
5XL
M
S

But I would like to sort this list into this order (from smallest size to largest):

S
M
2XL
5XL

The only way I can think of to do this is to have a hard-coded array of the sizes and to sort by their index, then when I need to grab the size value I can grab the size order array[i] value. But, as I said, I would prefer this order not to be hard-coded.

The reason I would like the order to be dynamic is the order items are loaded from files on the hard disk at runtime, and also added/edited/deleted by the user at run-time, and they may contain a size that I haven't hard-coded, for example I could hard code all the way from 10XS to 10XL but if someone adds the size "110cm" (aka a Medium), it will turn up somewhere in the order that I don't want it to, assuming the program doesn't crash and burn.

I can't quite wrap my head around how to do this.

like image 989
cjk84 Avatar asked Jun 08 '26 13:06

cjk84


1 Answers

Also, you could create a Dictionary<int, string> and add Key as Ordering order below. Leaving some gaps between Keys to accomodate new sizes for the future. Ex: if you want to add L (Large), you could add a new item as {15, "L"} without breaking the current order.

 Dictionary<int, string> mySizes = new Dictionary<int, string> { 
                                       { 20, "2XL" }, { 1, "S" },
                                       { 30, "5XL" }, { 10, "M" }
                                    };

 var sizes = mySizes.OrderBy(s => s.Key)
                    .Select(s => new {Size =  s.Value})
                    .ToList();
like image 155
Kaf Avatar answered Jun 10 '26 03:06

Kaf