繁体   English   中英

在.NET / C#中从数据库检索的子串值

[英]Substring value retrieved from database in .NET / C#

我正在使用以下内容从我的数据库中读出值:

    while (reader.Read())
    {
        newsLabel.Text += "<div style='float:left;'>" + reader["body"] + "</div>";
    }

我在想。 如何将“body”的值减少到0,0个字符?

我可以使用Substring函数吗?

非常感谢

假设body列包含一个字符串,你可以像这样截断它:

var body = (String) reader["body"];
var truncatedBody = body.Substring(0, Math.Min(body.Length, 20));

如果列可以为null ,则必须在调用Substring之前检查该列。

如果请求的子字符串长度超过实际字符串的长度,则子Substring 将抛出异常 这就是为什么你必须使用字符串长度和所需子字符串长度的最小值。

如果你这么做很多,你可以创建一个扩展方法:

public static class StringExtensions {

  public static String Truncate(this String str, Int32 length) {
    if (length < 0)
      throw new ArgumentOutOfRangeException("length");
    if (str == null)
      return String.Empty;
    return str.Substring(0, Math.Min(str.Length, length));
  }

}

你可以像这样使用它:

((String) reader["body"]).Truncate(20)

你可以这样做,如下所示。 一定要检查DbNull。

while (reader.Read()) 
        {
            string body = reader["body"] is DBNull ? "" : Convert.ToString(reader["body"]);

            if(body.Length > 20)
              body = body .Substring(0, 20);

            newsLabel.Text += "<div style='float:left;'>" + body  + "</div>";   
        }

是的,你可以在C#的Substring中做到这一点

newsLabel.Text += "<div style='float:left;'>" + Convert.ToString( reader["body"]).SubString(0,20) + "</div>";

阅读MSDN链接

reader["body"].ToString().Substring(0,20);

除了这里的所有答案之外,您还可以将此子字符串推送回数据库 - 因为SQL具有SubString函数。

例如,如果您使用的是Linq 2 Sql,那么c#SubString方法可以转换回数据库中的SQL操作 - http://weblogs.asp.net/dixin/archive/2010/04/15/understanding-linq-to -sql -4-数据检索-通过查询-methods.aspx

这是最佳还是需要取决于您的应用程序和数据库。

希望有所帮助

斯图尔特

while(reader.Read()) 
{
    string readBody = reader["body"] as string;
    if(!string.IsNullOrEmpty(readBody))
    {
        if(readBody.Length > 20)
           newsLabel.Text = string.Format("{0}<div style='float:left;'>{1}</div>",
                                     newsLabel.Text, readBody.Substring(0,20));
        else
           newsLabel.Text = string.Format("{0}<div style='float:left'>{1}</div>",
                                     newsLabel.Text, readBody);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM