c# - 包含数字和字母的排序字段

标签 c# linq sorting

我有一个 numbersnumber-letterletter-number 的列表。我列的类型是字符串。我的数据是像这样:

1
14
3
S-34
2
36-1/E
26
S-14
20
S-2
19
36-1
30
35
S-1
34

但我想这样排序:

1
2
3
14
20
25
30
35
36-1
36-1/E
S-1
S-2
S-14
S-34

但是我的代码是这样对数据进行排序的:

1
14
19
2
20
25
3
30
35
36-1
36-1/E
S-1
S-14
S-2
S-34

我的代码是:

List<ViewTestPackageHistorySheet> lstTestPackageHistorySheets = _reportTestPackageHistorySheetRepository.ShowReport(Id).OrderBy(i => i.JointNumber).ToList();

我更改了下面的代码但失败了。

List<ViewTestPackageHistorySheet> lstTestPackageHistorySheets = _reportTestPackageHistorySheetRepository.ShowReport(Id).OrderBy(i => Convert.ToInt32(i.JointNumber)).ToList();

错误是:

LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression.

最佳答案

使用以下字母数字排序器,它在内部使用 PInvoke

public class AlphaNumericSorter : IComparer<string>
{
    public int Compare(string x, string y)
    {
        return SafeNativeMethods.StrCmpLogicalW(x, y);
    }
}

[SuppressUnmanagedCodeSecurity]
internal static class SafeNativeMethods
{
    [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
    public static extern int StrCmpLogicalW(string psz1, string psz2);
}

用法:

List<string> testList = // Your input list;

testList.Sort(new AlphaNumericSorter());

现在 testList 包含问题中预期的排序数据

关于c# - 包含数字和字母的排序字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39011859/

相关文章:

perl - 使用 perl 进行高级排序

c# - GetDirectories 返回路径\\目录

c# - 获取 XML 元素

python - python中的字典排序列表

linux - linux 中的排序命令首先对特殊字符进行排序,而不是小写和大写。

c# - 如何使用 LINQ 将泛型序列转换为三角形?

c# - ASP.NET 5 跨平台,老式 DLL 将何去何从?

c# - SQL Server 2008 + .NET3.5 + LINQ 中出现 "Server failed to resume the transaction"错误

c# - 如何在 C# 中限制对其容器的嵌套类的访问?

c# - 从表单更新 LINQ 模型的最佳方法