使用LINQ的OrderBy对具有包含数字和字符的项的List <string>进行排序无法正常工作

时间:2019-07-08 07:29:20

标签: c# linq sorting natural-sort

我尝试了具有数字和字符的C#排序顺序。

List<EmployeesSTPList> employeeList = new List<EmployeesSTPList>();

employeeList.Add(new EmployeesSTPList { ID = "2", Name = "Employee 2" });
employeeList.Add(new EmployeesSTPList { ID = "1", Name = "Employee 1" });
employeeList.Add(new EmployeesSTPList { ID = "3", Name = "Employee 3" });
employeeList.Add(new EmployeesSTPList { ID = "10", Name = "Employee 10" });
employeeList.Add(new EmployeesSTPList { ID = "EMP002", Name = "Employee 02" });
employeeList.Add(new EmployeesSTPList { ID = "EMP003", Name = "Employee 03" });
employeeList.Add(new EmployeesSTPList { ID = "11", Name = "Employee 11" });
employeeList.Add(new EmployeesSTPList { ID = "4", Name = "Employee 4" });
employeeList.Add(new EmployeesSTPList { ID = "EMP010", Name = "Employee 010" });
employeeList.Add(new EmployeesSTPList { ID = "EMP001", Name = "Employee 01" });
employeeList.Add(new EmployeesSTPList { ID = "EMP011", Name = "Employee 011" });

employeeList = employeeList.OrderBy(a => a.ID, StringComparer.Ordinal).ToList();

foreach (var item in employeeList)
{
    <div> @item.ID</div>
}

输出为:

1
10
11
2
3
4
EMP001
EMP002
EMP003
EMP010
EMP011

但希望如此,

1
2
3
4
10
11
EMP001
EMP002
EMP003
EMP010
EMP011

我已经使用 StringComparer.Ordinal string[]进行了同样的尝试,效果很好。但是我的模型数据包含在列表中。

1 个答案:

答案 0 :(得分:0)

StringComparer.Ordinal在排序之前不检查字符串是否为数字。而是,它执行以下操作:

  

执行独立于语言的简单字节比较。比较比较以编程方式生成的字符串或比较区分大小写的资源(例如密码)时,这是最合适的。

您将需要一个自定义比较器,该比较器首先检查字符串是否为数字。可能使用正则表达式。