c# - 如何在不删除变音符号的情况下使用变音符号对列表进行排序

标签 c# sorting diacritics

如何对包含带有变音符号的字母的列表进行排序?

此示例中使用的单词是编造的。

现在我得到一个显示这个的列表:

  • báb
  • baz
  • bez

但我想得到一个显示这个的列表:

  • baz
  • báb
  • bez

将变音符号单独显示为一个字母。 有没有办法在 C# 中执行此操作?

最佳答案

如果您将当前线程的文化设置为您想要排序的语言,那么这应该会自动运行(假设您不想要一些特殊的自定义排序顺序)。像这样

List<string> mylist;
....
Thread.CurrentThread.CurrentCulture = new CultureInfo("pl-PL");
mylist.Sort();

应该让您得到根据波兰文化设置排序的列表。

更新:如果文化设置没有按照您想要的方式对其进行排序,那么另一种选择是实现您自己的字符串比较器。

更新 2:字符串比较器示例:

public class DiacriticStringComparer : IComparer<string>
{
    private static readonly HashSet<char> _Specials = new HashSet<char> { 'é', 'ń', 'ó', 'ú' };

    public int Compare(string x, string y)
    {
        // handle special cases first: x == null and/or y == null,  x.Equals(y)
        ...

        var lengthToCompare = Math.Min(x.Length, y.Length);
        for (int i = 0; i < lengthToCompare; ++i)
        {
            var cx = x[i];
            var cy = y[i];

            if (cx == cy) continue;

            if (_Specials.Contains(cx) || _Specials.Contains(cy))
            {
                // handle special diacritics comparison
                ...
            }
            else
            {
                // cx must be unequal to cy -> can only be larger or smaller
                return cx < cy ? -1 : 1;
            }
        }
        // once we are here the strings are equal up to lengthToCompare characters
        // we have already dealt with the strings being equal so now one must be shorter than the other
        return x.Length < y.Length ? -1 : 1;
    }
}

免责声明:我还没有测试过它,但它应该能让您大致了解。此外,char.CompareTo() 不会按字典顺序进行比较,但根据我发现的一个来源,< 和 > 确实如此 - 虽然不能保证。最坏的情况是您必须将 cxcy 转换为字符串,然后使用默认的字符串比较。

关于c# - 如何在不删除变音符号的情况下使用变音符号对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5447422/

相关文章:

c# - 将鼠标指针移动到选项卡按钮将您带到的位置 C#

c# - JToken 序列化为字符串 json.net

c# - StreamReader 和二进制数据

c# - 使用 MarshalByRefObject 的 [Serializable] 属性或子类化?

scala - Scala排序是否稳定?

java - 使用 lambda 函数对数组列表进行排序不起作用

javascript - 如何对所有行的每列数组进行多重排序? (JavaScript)

.net - 如何从 .NET 中的字符串中删除变音符号(重音符号)?

Phpmailer 遇到变音问题

python - 阅读带重音的文本 - Python