字母数字排序的使用LINQ [英] Alphanumeric sorting using LINQ

查看:252
本文介绍了字母数字排序的使用LINQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的String [] ,其中每个元素与一些数值结束。

 的String [] = partNumbers新的String []
{
    ABC10,ABC1,ABC2,ABC11,ABC10,AB1,AB 2,AB11
};

我想上面的阵列使用如下排序 LINQ ,但我没有得到预期的结果。

  VAR的结果= partNumbers.OrderBy(X => X);

实际结果:


  

AB1结果
  AB11结果
  AB2结果
  ABC1结果
  ABC10结果
  ABC10结果
  ABC11结果
  ABC2


预期结果


  

AB1结果
  AB2结果
  AB11结果
  ..



解决方案

这是因为字符串默认的排序是标准的字母数字字典(字典)排序,因为总是下令从左至右进行ABC11会ABC2之前。

要得到你想要的,你需要垫by子句中您的订单数字部分,是这样的:

  VAR的结果= partNumbers.OrderBy(X => PadNumbers(X));

其中, PadNumbers 可以定义为:

 公共静态字符串PadNumbers(字符串输入)
{
    返回Regex.Replace(输入[0-9] +匹配= GT; match.Value.PadLeft(10'0'));
}

这是出现在输入字符串,以便排序依据看到任何数量的这片零(或数字):

  ABC0000000010
ABC0000000001
...
AB0000000011

的填充只发生在用于比较的密钥。原来的字符串(不填充)都在结果pserved $ P $。

请注意,这种方法假定的位的最大数量为输入数字。

I have a string[] in which every elements ends with some numeric value.

string[] partNumbers = new string[] 
{ 
    "ABC10", "ABC1","ABC2", "ABC11","ABC10", "AB1", "AB2", "Ab11" 
};

I am trying to sort the above array as follows using LINQ but I am not getting the expected result.

var result = partNumbers.OrderBy(x => x);

Actual Result:

AB1
Ab11
AB2
ABC1
ABC10
ABC10
ABC11
ABC2

Expected Result

AB1
AB2
AB11
..

解决方案

That is because the default ordering for string is standard alpha numeric dictionary (lexicographic) ordering, and ABC11 will come before ABC2 because ordering always proceeds from left to right.

To get what you want, you need to pad the numeric portion in your order by clause, something like:

 var result = partNumbers.OrderBy(x => PadNumbers(x));

where PadNumbers could be defined as:

public static string PadNumbers(string input)
{
    return Regex.Replace(input, "[0-9]+", match => match.Value.PadLeft(10, '0'));
}

This pads zeros for any number (or numbers) that appear in the input string so that OrderBy sees:

ABC0000000010
ABC0000000001
...
AB0000000011

The padding only happens on the key used for comparison. The original strings (without padding) are preserved in the result.

Note that this approach assumes a maximum number of digits for numbers in the input.

这篇关于字母数字排序的使用LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆