Null Exception handling in foreach loop

2019-09-21 06:17发布

I am having the list X with some string and null value . I am iterating the foreach loop to bind the value to the textbox. If I get any null values in my list X the foreach loop get terminated and getting the null exception how to handle it.

I am checking the condition inside the for each loop. but i tnink it not correct logcally.

SPList _listObj = web.Lists[new Guid(listID)];
            SPListItem item = _listObj.GetItemById(Convert.ToInt32(itemID));
           foreach (SPField field in _listObj.Fields)
            {
                if (field.Title != Null)
                {  //do some code}}

6条回答
小情绪 Triste *
2楼-- · 2019-09-21 06:49

Why don't you use it like this with null-coalescing operator

   foreach (var item in feeList ?? new List<FeeBusiness>())
   {
           // your code
   }

The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.

查看更多
混吃等死
3楼-- · 2019-09-21 06:50

Try below code:

foreach(var x in Lists.Where(x => x.fiels != null))
{

}
查看更多
一夜七次
4楼-- · 2019-09-21 06:54

That code looks pretty suspicious to me.

Firstly, do you really have a list of lists? If so, I'd imagine you have to iterate over each element in the inner list as well:

foreach(List list in Lists)
{
    foreach (var x in list)
    {
        if (x.fields != null)
            // blah
        else
            // blah
    }
}

Secondly, are you sure that the Lists variable doesn't contain any nulls? Possibly it's actually x which is null, and that's the cause of your Null Reference Exception:

foreach(List x in Lists)
{
    if (x != null && x.fields != null)
        // blah
    else
        // blah
}
查看更多
姐就是有狂的资本
5楼-- · 2019-09-21 06:54

List x in Lists? You probably mean to do:

foreach(string x in listvar){
    if(x != null)
       // do something
}

And are the strings actually null or just empty? That is a difference.

foreach(string x in listvar){
    if(x != "")
       // do something
}

I suspect that the problem is in your incorrect implementation of the foreach loop which causes to pop null errors as the objects inside the loop do not exist.

查看更多
闹够了就滚
6楼-- · 2019-09-21 06:58

The code provided is not correct. I suppose you want to check X for Null in foreach loop. If this is logically correct or not, instead only you may know as logic goes beyond the code provided and depends on where you actually use it.

I personally don't find nothing bad to check for nulls in foreach loop.

You also, for example, can use Linq to query first for Null values and after Non Null values. The matter of design choice.

Regards.

查看更多
Bombasti
7楼-- · 2019-09-21 06:58
string delimitedvalues = null;//"11,22,33";
foreach(var str in (delimitedvalues?? string.Empty).split(','))
{
    string testvalue = "Test Value" + str;
}

Hope the above construct is useful!

查看更多
登录 后发表回答