加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 按文化排序不按预期工作

发布时间:2020-12-15 22:35:43 所属栏目:百科 来源:网络整理
导读:为什么“ū”首先代替“U”? CultureInfo ci = CultureInfo.GetCultureInfo("lt-LT"); bool ignoreCase = true; //whether comparison should be case-sensitive StringComparer comp = StringComparer.Create(ci,ignoreCase); string[] unordered = { "Za"
为什么“ū”首先代替“U”?

CultureInfo ci = CultureInfo.GetCultureInfo("lt-LT");
    bool ignoreCase = true; //whether comparison should be case-sensitive
    StringComparer comp = StringComparer.Create(ci,ignoreCase);
    string[] unordered = { "Za","?b","ūa","Ub" };
    var ordered = unordered.OrderBy(s => s,comp);

订购结果:
UA
UB
ZA
ZB

应该是:UbūaZa?b

这是立陶宛字母的顺序. https://www.assorti.lt/userfiles/uploader/no/norvegiska-lietuviska-delione-abecele-maxi-3-7-m-vaikams-larsen.jpg

解决方法

我刚刚为你的问题做了一个(有限的)解决方案.
这不是优化的,但它可以给出如何解决它的想法.
我创建一个LithuanianString类,它只用于封装你的字符串.
此类实现IComparable以便能够对LithuanianString列表进行排序.

这可能是班级:

public class LithuanianString : IComparable<LithuanianString>
{

    const string UpperAlphabet = "A?BC?DE??FGHI?YJKLMNOPRS?TU?ūVZ?";
    const string LowerAlphabet = "a?bc?de??fghi?yjklmnoprs?tu?ūvz?";
    public string String;

    public LithuanianString(string inputString)
    {
        this.String = inputString;
    }

    public int CompareTo(LithuanianString other)
    {
        var maxIndex = this.String.Length <= other.String.Length ? this.String.Length : other.String.Length;
        for (var i = 0; i < maxIndex; i++)
        {
            //We make the method non case sensitive
            var indexOfThis = LowerAlphabet.Contains(this.String[i])
                ? LowerAlphabet.IndexOf(this.String[i])
                : UpperAlphabet.IndexOf(this.String[i]);

            var indexOfOther = LowerAlphabet.Contains(other.String[i])
                ? LowerAlphabet.IndexOf(other.String[i])
                : UpperAlphabet.IndexOf(other.String[i]);

            if (indexOfOther != indexOfThis)
                return indexOfThis - indexOfOther;
        }
        return this.String.Length - other.String.Length;
    }
}

以下是我尝试的示例:

static void Main(string[] args)
    {
        string[] unordered = { "Za","Ub" };

        //Create a list of lithuanian string from your array
        var lithuanianStringList = (from unorderedString in unordered
            select new LithuanianString(unorderedString)).ToList();
        //Sort it 
        lithuanianStringList.Sort();

        //Display it
        Console.WriteLine(Environment.NewLine + "My Comparison");
        lithuanianStringList.ForEach(c => Console.WriteLine(c.String));
    }

输出是预期的:

Ub ūa Za ?b

此类允许仅通过替换开头定义的两个常量中的字符来创建自定义字母表.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读