thomas
thomas

Reputation: 2642

C# sort string of comma separated numbers

In C# what would you consider the fastest way to do this? The code will ultimately be part of a SQL Server CLR C# user defined function, but I don't think that is important for this question.

INPUT:  "1,3,2,5,4"
OUTPUT: "1,2,3,4,5"

The sorting has to be done by comparing the numbers as ints, not strings or chars.

I currently have the following but it is sorting based on strings, not ints. I could introduce a custom comparer but figure I would ask the question to see if others have any ideas before I do that.

[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString udfSortDimensionValueIDString(SqlString DimensionValueIDs)
{
    string[] values = ((string)DimensionValueIDs).Split(',');
    Array.Sort(values);
    return String.Join(",", values);
}

Using .NET 3.5 if that matters.

Upvotes: 4

Views: 8267

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186718

You can use Linq:

  using System.Linq; // no include required, just uses the namespace

  ...

  String Input = "1,3,2,5,4";

  String Output = String.Join(",", Input
    .Split(',')
    .Select(x => int.Parse(x))
    .OrderBy(x => x));

Upvotes: 12

Adam
Adam

Reputation: 186

You can split the string on the commas and convert each string to a number using the Convert library. http://msdn.microsoft.com/en-us/library/bb397679.aspx

Upvotes: 0

Rik
Rik

Reputation: 29243

string s = "1,3,2,5,4";
string ordered = String.Join(",", s.Split(',').Select(c => Convert.ToInt32(c)).OrderBy(i=>i));

Upvotes: 2

Related Questions