在一般的弱类型语言中,比如javascript中,我们可以直接按照如下代码排序,正常的排序结果如下
var array=["UnderwearMdseId", "timestamp", "message", "client", "ToolMdseId", "PostureId"];
console.log(array.sort());
//["PostureId", "ToolMdseId", "UnderwearMdseId", "client", "message", "timestamp"]
如果我们想利用linq的排序来达到类似的效果,那么需要考虑如下的代码
class NameComparer : IComparer<string>
{
public int Compare(string x, string y)
{
return string.Compare(x, y, StringComparison.Ordinal);
}
}
class Program
{
static void Main(string[] args)
{
List<string> list = new List<string>() { "UnderwearMdseId", "timestamp", "message", "client", "ToolMdseId", "PostureId" };
list = list.OrderBy(a => a, new NameComparer()).ToList();
}
}
官方解释如下
-
An ordinal sort compares strings based on the numeric value of each
Char
object in the string. An ordinal comparison is automatically case-sensitive because the lowercase and uppercase versions of a character have different code points. However, if case is not important, you can specify an ordinal comparison that ignores case. This is equivalent to converting the string to uppercase by using the invariant culture and then performing an ordinal comparison on the result. For a list of the
String
methods that compare two strings using ordinal sort rules, see the
String operations by category
section. -
来自http://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspx