c#实现自然排序效果,按1,2,11而不是1,11,12,区分字母文字和数字

时间:2024-10-09 21:07:03

排序有时候要考虑后缀。这样看起来比较自然。

参考了codeproject上一篇文章:http://www.codeproject.com/Articles/22978/Implementing-the-NET-IComparer-interface-to-get-a

然后自己写了个简单的,考虑到主要思想是上面那个文章上的,所以不做太多解释。代码如下:

 using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions; namespace StringOrder
{
class Program
{
static void Main(string[] args)
{
string[] array = new string[] { "2.1", "2.001" }; string[] array2 = array.OrderBy(a => a, new StringCompare1()).ToArray();
Console.Read(); }
}
public class StringCompare1 : IComparer<string>
{
public int Compare(string x, string y)
{ StringParser sx = new StringParser(x);
StringParser sy = new StringParser(y);
while (sx.TokenType != StringParser.ETokenType.Nothing || sy.TokenType != StringParser.ETokenType.Nothing)
{
if (sx.TokenType == StringParser.ETokenType.Numberic && sy.TokenType == StringParser.ETokenType.Numberic)
{
return decimal.Compare(sx.DoubleValue,sy.DoubleValue);
}
if (string.Compare(sx.StringValue, sy.StringValue) != )
{
return string.Compare(sx.StringValue, sy.StringValue);
}
else
{
sx.NextToken();
sy.NextToken();
}
}
return ;
}
} public class StringParser
{
private string _value;
private char _curChar;
private int _curIndex = ;
private int _length;
private ETokenType _tokenType = ETokenType.Character;
public ETokenType TokenType { get { return _tokenType; } } private string _stringValue;
public string StringValue { get { return _stringValue; } } private decimal _doubleValue;
public decimal DoubleValue { get { return _doubleValue; } } public StringParser(string val)
{
_value = val;
_length = val.Length;
NextChar();
NextToken();
} public void NextToken()
{
if (_curChar == '\0')
{
_tokenType = ETokenType.Nothing;
_stringValue = null;
}
else if (char.IsDigit(_curChar))
{
int startIndex = _curIndex;
while (char.IsDigit(_curChar) || _curChar == '.')
{
NextChar();
}
string temp = _value.Substring(startIndex-, _length - startIndex+);
if (decimal.TryParse(temp, out _doubleValue))
{
_tokenType = ETokenType.Numberic;
}
else
{
_tokenType = ETokenType.Character;
}
_stringValue = temp;
}
else if (char.IsLetter(_curChar))
{
_tokenType = ETokenType.Character;
int startIndex = _curIndex;
while (char.IsLetter(_curChar))
{
NextChar();
}
_stringValue = _value.Substring(startIndex-,_curIndex-startIndex);
}
else
{
NextChar();
}
} private void NextChar()
{
if (_curIndex >= _length)
{
_curChar = '\0';
return;
}
else
{
_curChar = _value[_curIndex];
_curIndex += ;
} }
public enum ETokenType
{
Nothing,
Character,
Numberic,
}
}
}

另可参考:

http://www.codeproject.com/Articles/22175/Sorting-Strings-for-Humans-with-IComparer

感谢每一位阅读此篇文章的人,希望可以帮到你。