在foreach语句中处理Null [英] Handle Nulls in foreach statement

查看:138
本文介绍了在foreach语句中处理Null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请建议我如何在foreach循环中处理DBNUll值.以下是我的代码

Please suggest me how to handle DBNUll values in foreach loop. Below is my code

foreach (string  s in dr.Row.ItemArray)
{
    sb.Append(s);
    sb.Append("/t");
}



我的项目数组具有DBNull值.所以我遇到了错误.如何解决此问题.

在获取字符串"s"的值时,我遇到了错误.不在循环之内...!



My item array have DBNull values. So I''m getting error.How to resolve this.

here at the time of getting value to string "s", I''m getting the error. not inside the loop...!

推荐答案

我的答案基于您的问题详细信息和解决方案1中的注释.
My Answer based on your Question details and comments in Solution-1.
报价:

我可以按照您的建议进行操作,如果我能够进入循环,我可以这样做,但是在将值分配给字符串"s"的时间,但出现错误.

I can do the same what you suggested, If I''m able to enter inside the loop i can do like this but at the time of assigning value to string"s" I''m getting the error.


我怀疑您的语法正确无误,并且事件在编译时没有错误.

请查看下面的链接,以获取DataRow.ItemArray属性的正确语法.

http://msdn.microsoft.com/en-us/library/system. data.datarow.itemarray.aspx

属性DataRow.ItemArray返回object的数组.

您可以尝试如下更改代码.


I doubt your Syntax is correct and event it is compiling without Error.

Have a look at below link for proper syntax of DataRow.ItemArray Property.

http://msdn.microsoft.com/en-us/library/system.data.datarow.itemarray.aspx

Property DataRow.ItemArray returns Array of object.

You may try by changing your code as below.

DataRow dr = null;
StringBuilder sb = new StringBuilder();
//Assign some data to your dr here.
                
foreach (object o in dr.ItemArray)
{
  if (o != null && o != DBNull.Value)
  {
    sb.Append(Convert.ToString(o));
    sb.Append("/t");
  }
}


好吧,我不会对数据库造成太多混乱,但是这样的事情可能会有所帮助

Well I don''t mess with databases too much but something like this may help

foreach (string s in dr.Row.ItemArray)
{
    if (s != System.DBNull.Value)
    {
        sb.Append(s);
        sb.Append("/t");
    }
}


我会做类似的事情

I would do something like this

foreach(object o in dr.Row.ItemArray)
{
    if(o!=DBNull)
    {
        sb.Append(o.ToString());
        sb.Append("/t");
    }
}



您的错误是因为没有从DBNull到字符串的隐式转换. (我想!)



Your error is because there is no implicit conversion from DBNull to string. (I think!)


这篇关于在foreach语句中处理Null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆