我正在尝试对字母数字值列表进行排序,换言之,包含数字和字符串的列表
示例:BOB10,BOT20,ETC ......
List<Object> myList = _items.OrderBy(x => x.FirstName).ToList();
_items= new List<Object>(myList);
但输出仍然是:BOT20,BOB10
出了什么问题?
答案 0 :(得分:0)
第一: 尝试使用字母数字算法, 首先在新类中实现算法,而不是这样做:
List<Object> yourList = new List < Object >(thePreviousList.OrderBy(x => x.FirstName, new AlphanumComparatorFast()).ToList())
正如这里所解释的那样:
http://www.dotnetperls.com/alphanumeric-sorting
通过创建新类来实现算法 AlphanumComparatorFast ,而不仅仅是调用它
编辑:
下面的alpha算法:
Public class AlphanumComparatorFast : IComparer
{
public int Compare(object x, object y)
{
string s1 = x as string;
if (s1 == null)
{
return 0;
}
string s2 = y as string;
if (s2 == null)
{
return 0;
}
int len1 = s1.Length;
int len2 = s2.Length;
int marker1 = 0;
int marker2 = 0;
// Walk through two the strings with two markers.
while (marker1 < len1 && marker2 < len2)
{
char ch1 = s1[marker1];
char ch2 = s2[marker2];
// Some buffers we can build up characters in for each chunk.
char[] space1 = new char[len1];
int loc1 = 0;
char[] space2 = new char[len2];
int loc2 = 0;
// Walk through all following characters that are digits or
// characters in BOTH strings starting at the appropriate marker.
// Collect char arrays.
do
{
space1[loc1++] = ch1;
marker1++;
if (marker1 < len1)
{
ch1 = s1[marker1];
}
else
{
break;
}
} while (char.IsDigit(ch1) == char.IsDigit(space1[0]));
do
{
space2[loc2++] = ch2;
marker2++;
if (marker2 < len2)
{
ch2 = s2[marker2];
}
else
{
break;
}
} while (char.IsDigit(ch2) == char.IsDigit(space2[0]));
// If we have collected numbers, compare them numerically.
// Otherwise, if we have strings, compare them alphabetically.
string str1 = new string(space1);
string str2 = new string(space2);
int result;
if (char.IsDigit(space1[0]) && char.IsDigit(space2[0]))
{
int thisNumericChunk = int.Parse(str1);
int thatNumericChunk = int.Parse(str2);
result = thisNumericChunk.CompareTo(thatNumericChunk);
}
else
{
result = str1.CompareTo(str2);
}
if (result != 0)
{
return result;
}
}
return len1 - len2;
}
}
答案 1 :(得分:0)
为什么不使用List.Sort()而不是OrderBy?
using System;
using System.Collections.Generic;
namespace Test {
static class Program {
static void Main() {
List<string> list = new List<string>() {"BOT20", "BOB10", "BUG40", "BAG90"};
list.Sort();
foreach(var el in list) {
Console.Write(el + ">");
}
}
}
}
输出:BAG90>BOB10>BOT20>BUG40>