如下面的代码
List<string> arrays = new List<string>();
arrays.Add("2");
arrays.Add("6");
arrays.Add("4");
arrays.Add("98");
arrays.Add("5");
arrays.Add("16");
arrays.Add("9");
arrays.Add("8");
arrays.Add("7");
arrays.Add("44"); Console.WriteLine("Before:");
foreach (string item in arrays)
{
Console.Write(item);
Console.Write(" ");
} Console.WriteLine();
Console.WriteLine("After sort:"); arrays.Sort();
foreach (string item in arrays)
{
Console.Write(item);
Console.Write(" ");
}
调用Sort()方法排序后,为什么输出以下结果
Before:
2 6 4 98 5 16 9 8 7 44
After sort:
16 2 4 44 5 6 7 8 9 98 4
而不是
Before:
2 6 4 98 5 16 9 8 7 44
After sort:
2 4 5 6 7 8 9 16 44 98
List<string> arrays = new List<string>();
arrays.Add("2");
arrays.Add("6");
arrays.Add("4");
arrays.Add("98");
arrays.Add("5");
arrays.Add("16");
arrays.Add("9");
arrays.Add("8");
arrays.Add("7");
arrays.Add("44"); Console.WriteLine("Before:");
foreach (string item in arrays)
{
Console.Write(item);
Console.Write(" ");
} Console.WriteLine();
Console.WriteLine("After sort:"); arrays.Sort();
foreach (string item in arrays)
{
Console.Write(item);
Console.Write(" ");
}
调用Sort()方法排序后,为什么输出以下结果
Before:
2 6 4 98 5 16 9 8 7 44
After sort:
16 2 4 44 5 6 7 8 9 98 4
而不是
Before:
2 6 4 98 5 16 9 8 7 44
After sort:
2 4 5 6 7 8 9 16 44 98
把字符串 转换成int 就行了
字符串是按ASCII排序,
你可以用委托定义自己的排序方法:
arrays.Sort(delegate(string x, string y)
{
int a, b;
// 如果可以转换成数值,就按数值排序,否则按字符串排序
if (int.TryParse(x, out a) && int.TryParse(y, out b))
return a.CompareTo(b);
else
return x.CompareTo(y);
});
下面的代码就是正常的,MSDN上的
List<string> dinosaurs = new List<string>(); dinosaurs.Add("Pachycephalosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
调用Sort方法后,结果是
Amargasaurus
Deinonychus
Mamenchisaurus
Pachycephalosaurus突然明白了,这个函数比较的是第一个字符的ASCII码,那我要完成这样的功能似乎得自己写方法了?
直到不相同的那个字符,按ASCII值进行排序
1.txt
2.txt
3.txt
4.txt
5.txt
6.txt
7.txt
8.txt
9.txt
10.txt
那么排序后一定是
1.txt
10.txt
2.txt
3.txt
4.txt
5.txt
6.txt
7.txt
8.txt
9.txt
// 如果返回0,表示2个元素相等,返回负数,表示x小于y;返回正数,表示x大于y
// 所以这个匿名函数里,你可以执行任意代码,只要返回一个整数即可,一般是-1,0,1
arrays.Sort(delegate(string x, string y)
{
return x.CompareTo(y);
});
你可以用int泛型
List <int> arrays = new List <int>();
arrays.Add(int.Parse("字符串"));
要是既有字符串又有数字 而且数字在前边
可以参考001.txt
002.txt
003.txt
004.txt
005.txt
006.txt
007.txt
008.txt
009.txt
010.txt 这样排出来的就是正确的了
是这个意思么,我刚试了,是这样写的 Console.WriteLine("After sort:"); arrays.Sort(delegate(string x, string y)
{
return x.CompareTo(y);
}); foreach (string item in arrays)
{
Console.Write(item);
Console.Write(" ");
}
结果还是一样的。。
16 2 4 44 5 6 7 8 9 98 4
是这个意思么,我刚试了,是这样写的 Console.WriteLine("After sort:"); arrays.Sort(delegate(string x, string y)
{
return x.CompareTo(y);
}); foreach (string item in arrays)
{
Console.Write(item);
Console.Write(" ");
}
结果还是一样的。。
16 2 4 44 5 6 7 8 9 98 4
Convert.ToString();