使用LINQ和Function自定义排序

The*_*kal 1 c# linq sorting

我有一个字符串列表,每个字符串长度恰好是2个字符.我希望对它进行排序.我首先使用每个字符串的第一个字符对列表进行排序

.OrderBy(e => e[0])
Run Code Online (Sandbox Code Playgroud)

但我的问题是在排序第二个字符时,例如:

.ThenBy(string1 => string1, string2 => string2 Compare(string1,string2)
Run Code Online (Sandbox Code Playgroud)

我想选择两个字符串并将它们传递给我创建的名为compare的函数.

有人能告诉我如何做到这一点,或者是否有更好的方法来做我想做的事情?请分享.

public string sortT(string h)
{
    var sortedList = l
                    .OrderBy(e => e[0])
                    .ThenBy()
                    .ToList<string>();
    return sb.ToString();
}
private int Compare(string a, string b)
{
    List<char> value = new List<char>() {
        '2', '3', '4', '5', '6', '7', '8', '9','J','Q', 'K', 'A' };           
    if (value.IndexOf(a[1]) > value.IndexOf(b[1]))
        return 1; 
    return -1;
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 5

您可以使用列表作为基础:

List<char> value = new List<char>() { '2', '3', '4', '5', '6', '7', '8', '9','J','Q', 'K', 'A' };

var sortedList = l.OrderBy(str => str[0])
                  .ThenBy(str => value.IndexOf(str[1]))
                  .ToList<string>();
Run Code Online (Sandbox Code Playgroud)

您还可以实现这样的自定义IComparer<T>:

public class TwoCharComparer : IComparer<string>
{
    private static readonly List<char> value = new List<char>() { '2', '3', '4', '5', '6', '7', '8', '9', 'J', 'Q', 'K', 'A' };

    public int Compare(string x, string y)
    {
        if (x == null || y == null || x.Length < 2 || y.Length < 2) return 0; // ignore
        int comparison = x[0].CompareTo(y[0]);
        if (comparison != 0)
            return comparison;
        int ix1 = value.IndexOf(x[1]);
        int ix2 = value.IndexOf(y[1]);
        if(ix1 == ix2 && ix1 == -1)
            return x[1].CompareTo(y[1]);  
        else
            return ix1.CompareTo(ix2);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您可以传递List.Sort不需要创建新列表的内容:

var l = new List<string> { "C1", "B2", "A2", "B1", "A1", "C3", "C2" };
l.Sort(new TwoCharComparer()); // A1,A2,B1,B2,C1,C2,C3
Run Code Online (Sandbox Code Playgroud)