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

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

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


当前回答

要求“减少冗余”版本的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);
}

其他回答

我很喜欢Stu和samjudson解决方案中的元素,并将它们结合在一起,形成了我认为可用的组合:

public static string Ordinal(this int number)
{
    const string TH = "th";
    var s = number.ToString();
    
    number %= 100;
    
    if ((number >= 11) && (number <= 13))
    {
        return s + TH;
    }
   
    switch (number % 10)
    {
        case 1:
            return s + "st";
        case 2:
            return s + "nd";
        case 3:
            return s + "rd";
        default:
            return s + TH;
    }
}

你得自己动手了。在我的脑海中:

public static string Ordinal(this int number)
{
  var work = number.ToString();
  if ((number % 100) == 11 || (number % 100) == 12 || (number % 100) == 13)
    return work + "th";
  switch (number % 10)
  {
    case 1: work += "st"; break;
    case 2: work += "nd"; break;
    case 3: work += "rd"; break;
    default: work += "th"; break;
  }
  return work;
}

你可以这样做

Console.WriteLine(432.Ordinal());

针对11/12/13例外进行了编辑。我确实从我的头顶说过:-)

为1011编辑-其他人已经修复了这个问题,只是想确保其他人不会抓取这个错误的版本。

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" }})}"

本页为您提供了所有自定义数字格式规则的完整列表:

自定义数字格式字符串

如你所见,这里没有关于序数的内容,所以不能使用String.Format。然而,编写一个函数来实现它并不难。

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

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

更新:从技术上讲,序数不存在<= 0,所以我更新了上面的代码。还删除了多余的ToString()方法。

还要注意,这不是国际化的。我不知道其他语言中的序数是什么样子。

根据其他答案:

public static string Ordinal(int n)
{   
    int     r = n % 100,     m = n % 10;

    return (r<4 || r>20) && (m>0 && m<4) ? n+"  stndrd".Substring(m*2,2) : n+"th";                                              
}