Link to home
Start Free TrialLog in
Avatar of Dynotoe
Dynotoe

asked on

C# - Sorting an string ArrayList by the "Integer" number of the first comma delimited field

Hi everyone,

I have a rather large strig arraylist where each element represents a comma delimited text line which has a integer (long int) first field in the string.  For excample:

"148, Buy, open"
"35, sell, close"
Can someone show me how I can sort the arraylist by the first field integer number so that it is in "Numeric" oder?

Please let me give my gratitude in advance.

Thx very much.

Best - Dynottoe
Avatar of RyanAndres
RyanAndres
Flag of United States of America image

Array.Sort(YourArrayObject);
Avatar of Dynotoe
Dynotoe

ASKER

Hi Ryan,

What would be my "YourArrayObject" argument?
Hello Dynottoe,

Fortunately for you, with the number being first, your list will sort "automagically"! If your number came at the end of the string, this would be a little more difficult. This is because when the sort function looks at strings in a left-to-right fashion, the numbers will be evaluated first. For example:

Original list:
"148, Buy, open"
"35, sell, close"
"35, Buy, another open"

Sorted list:
"35, Buy, another open"
"35, sell, close"
"148, Buy, open"

You can perform the sort in the following fashion:

YourArrayList.Sort();

Now, what is neat about Sort is that you can pass it a custom function for determining order of strings being sorted...

Cheers,

NotLogical
Avatar of Dynotoe

ASKER

Hi Not Logical,

Well is there a way to ignor he rest of fthe csv string in the sort process?  My arraylist is huge and I need speed.  Any ideas?
Use a generic List rather than an ArrayList for type safety and increased performance.

Since you are reading in each line anyway you should just do a sort on the entire string because in the underlying code it stops  the comparison once it finds a difference.
List<string> str = new List<string>();
str.Add("148, Buy, open");
str.Add("35, sell, close");
str.Sort();

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of NotLogical
NotLogical
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Dynotoe

ASKER

"it stops  the comparison once it finds a difference."

of course why wouldn't it.  Very cool.

Ryan Check in 5 minutes, becasue I am askingh another sort question for 500 points but shouldn't be combined with this question.  If you can help me with that as well.

Thanks - Sean
Avatar of Mike Tomlinson
Also consider that you are still sorting a STRING so it will not evaluate the actual value of the integer.

Thus "2000000" will come before "30" because "2" is less than "3".

If you want it to correctly sort by the NUMERIC VALUES then you'll have to actually parse out the integer portion and properly convert it to a numeric data type do the comparison.