如何对char []列表进行排序?

gn6*_*n66 -2 .net c# arrays sorting list

我有以下列表:

List<char[]> list1 = new List<char[]>();
Run Code Online (Sandbox Code Playgroud)

我需要char[]对它们上的所有元素进行排序.如果我用list1.Sort()它说它无法比较元素,任何想法我该如何排序?

我真的需要列表char[]不是string.

Pat*_*man 7

如果您希望char[]在排序中具有确切的行为string,则可以执行以下操作:

list1 = list1.OrderBy(x => new string(x)).ToList();
Run Code Online (Sandbox Code Playgroud)


Tim*_*ter 5

您也可以List.Sort根据需要使用Patrick方法:

list1.Sort((chars1, chars2) => new string(chars1).CompareTo(new string(chars2)));
Run Code Online (Sandbox Code Playgroud)

这不需要创建新列表.

另一种方法是实现自己IComparer<T>Char[].这应该工作,虽然它肯定是可以改进和未经测试的.相关部分是Compare方法:

public class CharArrayComparer : IComparer<Char[]>, IEqualityComparer<Char[]>
{
    public CharArrayComparer() : this(false) {  }
    public CharArrayComparer(bool ignoreCase)
    {
        IgnoreCase = ignoreCase;
    }
    public bool IgnoreCase { get; set; }

    public int Compare(char[] x, char[] y)
    {
        if (x == null && y != null) return -1;
        if (y == null && x != null) return 1;
        if (y == null && x == null) return 0;
        int minLength = Math.Min(x.Length, y.Length);
        for(int i = 0; i < minLength; i++)
        {
            char c1 = IgnoreCase ? char.ToUpperInvariant(x[i]) : x[i];
            char c2 = IgnoreCase ? char.ToUpperInvariant(y[i]) : y[i];
            if (c1 < c2) return -1;
            else if (c2 < c1) return 1;
        }
        return 0;
    }

    public bool Equals(char[] x, char[] y)
    {
        if (x == null || y == null) return false;
        if (x.Length != y.Length) return false;
        for (int i = 0; i < x.Length; i++)
        {
            char c1 = IgnoreCase ? char.ToUpperInvariant(x[i]) : x[i];
            char c2 = IgnoreCase ? char.ToUpperInvariant(y[i]) : y[i];
            if (c1 != c2) return false;
        }
        return true;
    }

    public int GetHashCode(char[] chars)
    {
        if(chars == null) return 0;
        int hash = 17;
        unchecked
        {
            foreach (char c in chars)
            {
                if(IgnoreCase)
                    hash = hash * 31 + char.ToUpperInvariant(c).GetHashCode();
                else
                    hash = hash * 31 + c.GetHashCode();
            }
        }
        return hash;
    }
}
Run Code Online (Sandbox Code Playgroud)

它很容易List.Sort在许多LINQ扩展方法中使用:

list1.Sort(new CharArrayComparer());
Run Code Online (Sandbox Code Playgroud)