1. 程式人生 > >C#字串陣列中含數字時的排序

C#字串陣列中含數字時的排序

遇到這個問題時,從論壇看到的,放到這來做個記錄!

有個array:

string[333] fileList = {"list_1.htnl","list_10.html","list_100.html","list_101.html"......,"list_109.html","list_11.html"......}
意思就是,字串預設的排序並不是按照這種最末尾的數字排序的。

我想要生成排序為這樣的陣列.

string[333] fileList = {"list_1.htnl","list_2.html","list_3.html","list_4.html"......,"list_100.html","list_101.html"......}

就是排序是按照最末尾的那個數字的大小來排序。這個數字是遞增的。1---333。

解決方法:

void Main()
{
	  string[] fileList =new string[] {"list_1.htnl","list_10.html","list_100.html","list_111.html","list_109.html","list_11.html"};
		   fileList= fileList.OrderBy(s =>int.Parse( Regex.Match(s, @"\d+").Value)).ToArray();
		   foreach (string s in fileList)
		   {
			   Console.WriteLine(s);
		   }
}


/*
結果:
list_1.htnl
list_10.html
list_11.html
list_100.html
list_109.html
list_111.html

/*

使用Regex類需要引用名稱空間:using System.Text.RegularExpressions;