简体   繁体   English

C#对逗号分隔的数字进行排序

[英]C# sort string of comma separated numbers

In C# what would you consider the fastest way to do this? 在C#中,您认为最快的方法是什么? 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. 代码最终将成为SQL Server CLR C#用户定义函数的一部分,但我认为这对于这个问题并不重要。

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. 如果重要,请使用.NET 3.5。

You can use Linq : 你可以使用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));
string s = "1,3,2,5,4";
string ordered = String.Join(",", s.Split(',').Select(c => Convert.ToInt32(c)).OrderBy(i=>i));

You can split the string on the commas and convert each string to a number using the Convert library. 您可以在逗号上拆分字符串,并使用Convert库将每个字符串转换为数字。 http://msdn.microsoft.com/en-us/library/bb397679.aspx http://msdn.microsoft.com/en-us/library/bb397679.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM