为什么我得到一个"序列不包含任何元素"错误?

时间:2014-04-29 17:52:18

标签: c#

我使用以下内容将字符串的第一个字符转换为字符串,并在结尾处添加句点:

public static string toUpper (string mytext)
{
    if (string.IsNullOrEmpty(mytext) || mytext == "") return mytext;

    mytext = mytext.Trim();

    if (mytext.EndsWith("."))
    {
      mytext = mytext.First().ToString(CultureInfo.InvariantCulture).ToUpper()
             + string.Join("", mytext.Skip(1))
             ;
    }
    else
    {
      mytext = mytext.First().ToString(CultureInfo.InvariantCulture).ToUpper()
             + string.Join("", mytext.Skip(1))
             + "."
             ;
    }
    return mytext;
}

我收到错误如果mytext =“”,则序列中不包含任何元素:

 mytext = mytext.First().ToString(CultureInfo.InvariantCulture).ToUpper()
        + string.Join("", mytext.Skip(1))
        + "."
        ;

非常感谢您的建议。

5 个答案:

答案 0 :(得分:4)

在Trim()方法之后,您可能最终得到一个空字符串,当您尝试抓取第一个(不存在的)字符时会导致异常。

答案 1 :(得分:0)

在检查之前你应该修剪我的文本。 IsNullOrEmpty也可以独立使用'。所以试试:

mytext = mytext.Trim();
if (string.IsNullOrEmpty(mytext)) return mytext;

此外,如果mytext的长度为1个字符,则跳过(1)将失败。

答案 2 :(得分:0)

你的代码有bug。我按照以下方式修改了它

public static string toUpper(string mytext)
        {
            if (String.IsNullOrWhiteSpace(mytext)) { return mytext; }

            mytext = mytext.Trim();

            if (mytext.EndsWith("."))
            {
                if (mytext.Length == 1)
                {
                    return mytext;
                }
                else
                {
                    string first = mytext.First();
                    mytext = String.Join(first.ToUpper(), mytext.Substring(1));
                }
            }
            else
            {
                if (mytext.Length == 1)
                {
                    mytext = String.Join(mytext.ToUpper, ".");
                }
                else
                {
                    string first = mytext.First();
                    mytext = String.Join(first.ToUpper(), mytext.Substring(1));
                }

            }
            return mytext;
        }

答案 3 :(得分:0)

似乎比没有任何权利更复杂。

我追求优雅并使用正则表达式:

public static string toUpper( string s )
{
  string value = null ;
  if ( s != null )
  {
    // match length 1: it's the first first character: upper-case it
    // match length 0: the last character isn't a period. append it
    value = rx.Replace( s.Trim() , m => m.Length == 1 ? m.Value.ToUpper( CultureInfo.InvariantCulture ) : "." ) ;
  }
  return value ;
}
static readonly Regex rx = new Regex( @"(^.)|($(?<=[^\.]" ) ;

但你可以使用字符串构建器......

public static string toUpper( string s )
{
  if ( s == null ) return null ;

  StringBuilder sb = new StringBuilder( s.Trim() ) ;
  if ( sb.Length > 0 )
  {
    sb[0] = char.ToUpper(sb[0] , CultureInfo.InvariantCulture ) ;
    if ( sb[ sb.Length-1] != '.' ) sb.Append('.') ;
  }
  value = sb.ToString() ;
  return value ;
}

答案 4 :(得分:-3)

使用firstordefault()而不是first()。在没有元素的情况下首先抛出异常