在c#中有一个简单的方法来创建一个数字的序数吗?例如:

1返回第1位 2返回第2 3返回第3 等

这是否可以通过String.Format()来完成,或者是否有可用的函数来完成?


当前回答

又一个1号班轮。

public static string Ordinal(this int n)
{    
 return n + (new [] {"st","nd","rd" }.ElementAtOrDefault((((n + 90) % 100 - 10) % 10 - 1)) ?? "th");
}

其他回答

要求“减少冗余”版本的samjudson的回答…

public static string AddOrdinal(int number)
{
    if (number <= 0) return number.ToString();

    string GetIndicator(int num)
    {
        switch (num % 100)
        {
            case 11:
            case 12:
            case 13:
                return "th";
        }

        switch (num % 10)
        {
            case 1:
                return "st";
            case 2:
                return "nd";
            case 3:
                return "rd";
            default:
                return "th";
        }
    }

    return number + GetIndicator(number);
}

记得国际化!

这里的解决方案只适用于英语。如果您需要支持其他语言,事情就会变得复杂得多。

例如,在西班牙语中,“1st”可以写成“1”。o”、“1。”、“1。o”或“1”。比如“取决于你数的东西是阳性、阴性还是复数!”

因此,如果您的软件需要支持不同的语言,请尽量避免使用序数。

public static string OrdinalSuffix(int ordinal)
{
    //Because negatives won't work with modular division as expected:
    var abs = Math.Abs(ordinal); 

    var lastdigit = abs % 10; 

    return 
        //Catch 60% of cases (to infinity) in the first conditional:
        lastdigit > 3 || lastdigit == 0 || (abs % 100) - lastdigit == 10 ? "th" 
            : lastdigit == 1 ? "st" 
            : lastdigit == 2 ? "nd" 
            : "rd";
}

c# 8和9中接受的带有开关表达式和模式匹配的答案。

没有不必要的字符串转换或分配。

string.Concat(number, number < 0 ? "" : (number % 100) switch 
{   
    11 or 12 or 13 => "th", 
    int n => (n % 10) switch 
    { 
        1 => "st", 
        2 => "nd", 
        3 => "rd", 
        _ => "th", 
    }
})

或者是不友好的一句话:

$"{number}{(number < 0 ? "" : (number % 100) switch { 11 or 12 or 13 => "th", int n => (n % 10) switch { 1 => "st", 2 => "nd", 3 => "rd", _ => "th" }})}"
private static string GetOrd(int num) => $"{num}{(!(Range(11, 3).Any(n => n == num % 100) ^ Range(1, 3).All(n => n != num % 10)) ? new[] { "ˢᵗ", "ⁿᵈ", "ʳᵈ" }[num % 10 - 1] : "ᵗʰ")}";

如果有人在找一句俏皮话。