Reputation: 2402
I have a labelItem list that contains elements like : CARD1, CARD2, CARD10 ,CARD11
and I'm trying to sort them so I applied the sorting like below
List<LabelItem> sortedList = _labelItems.OrderBy(x => x.ViewLabel).ToList();
_labelItems = new BindingList<LabelItem>(sortedList);
But it doesn't sort it perfectly because the presence of the string CARD so it returns the list like CARD 1 , CARD10 , CARD11, CAR19 , CARD2 ,CARD21
I know that there is many good tools on how to split a string while using a natural sorting algo like in this link http://www.interact-sw.co.uk/iangblog/2007/12/13/natural-sorting
I'm finding it hard how to apply the split on this labelitem ( remove the string card ) and sort the list and make it return CARD1 , CARD2 CARD3 , CARD10 ,CARD11,CARD20 instead of CARD1 CARD10 CARD11 etc....
I appreciate help
Upvotes: 2
Views: 63
Reputation: 2402
I found what I was looking for , Indeed like you suggested Is good when I only have CARD in the list , then I discovered that No , it's not always a card It could be device and God only know what in the futur they might add
Plus , using like the basic sorting like the answer above will get the list sorted wrongly with ASCII sort
So the better approach is to implement like explained in http://www.dotnetperls.com/alphanumeric-sorting
Then All I did is sorting my BindingList like that
BindingList<LabelItem> sortedList = new BindingList<LabelItem>(_labelItems.OrderBy(x => x.Label, new AlphanumComparatorFast()).ToList());
Upvotes: 1
Reputation: 28737
You have to take out the string and convert the rest to a number:
List<LabelItem> sortedList = _labelItems.OrderBy(x => Convert.ToInt32(x.ViewLabel.Replace("CARD", "")).ToList();
_labelItems = new BindingList<LabelItem>(sortedList);
Note: This only works if you know that all your items start with word CARD
. If they don't, you need to find out a way to get the numbers out of there
Upvotes: 4