Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# sort string of comma separated numbers

Tags:

c#

sql-server

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.

like image 754
thomas Avatar asked Oct 21 '25 11:10

thomas


1 Answers

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));
like image 153
Dmitry Bychenko Avatar answered Oct 24 '25 02:10

Dmitry Bychenko