0

I have an array of string (concatarray) that is contains items such as

15.234 Mon 10, 20.12345 Tue 11, 11.3521 Wed 12, 1901.23 Thu 13

and I wish to sort it from largest number to smallest, like this

1901.23 Thu 13, 20.12345 Tue 11, 15.234 Mon 10, 11.3521 Wed 12

I tried

Array.Sort< string > (concatarray);

Array.Reverse(concatarray);

but that gets to

20.12345 Tue 11, 1901.23 Thu 13, 15.234 Mon 10, 11.3521 Wed 12

2
  • Are they always in the format <num>{ }<string>? Commented Apr 2, 2014 at 19:01
  • You will have to separate the number from the rest of the entry, then you can sort the numbers by comparing them to each other. Commented Apr 2, 2014 at 19:08

1 Answer 1

5

Sorting the strings will sort them using a text comparison. To sort on the number, you would extract the part of the string that is number and parse it to a double value:

concatarray =
  concatarray
  .OrderByDescending(i => Double.Parse(i.Split(' ', 2)[0], CultureInfo.InvariantCulture))
  .ToArray();
Sign up to request clarification or add additional context in comments.

6 Comments

Great answer, but can I ask why you choose double over float?
@Gray: I actually didn't consider using float, but some of the numbers in the example have seven digits of precision, which is right at the limit of what the float type can handle. It's plausible that other values in the data have even more digits. The CPU uses double internally for all floating point operations, so if you use float the values will be converted to double whenever they are used, so double is a more natural choice for values to work with.
thank you for your answer. It compiled successfully, but when I ran it, it gave me an error saying System.Form at Exception: Input string was not in a correct format.
@theGlitch: That means that you have some strings in your data that are not following the format in your example.
@Guffa I realized what was causing it. It was split by a _ rather than a space . I fixed it and it worked. Another question, but is there a way to split the double and the date into two arrays?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.