简体   繁体   中英

c# avoid checking for nulls when using iterating over collections

private void CheckForNewItems()
    {
        var items = GetChangedItems();
        if (items != null)
        {
            foreach (var item in items )
            {
                var itemDB= GetItem(item.id);
                if (itemDB!=null)
                {
                    itemDB.somevalue= item.somevalue;
                    SaveToDatabase(itemDB);

                }
            }
        }
    }

I Write alot of code similar to the code above. Is there a smarter way to check for nulls in this scenario? Is "if(item!=null)" effecient? Do i even have to check for nulls?

Regards

You can do it with some linq:

var items = GetChangedItems();

if (items == null)
    return;

var existingItems = items
    // create a new call that holds both objects
    .Select(i => new { ItemDB = GetItem(i.id), Item = i })
    // where the itemdb can be found.
    .Where(i => i.ItemDB != null);

foreach (var item in existingItems)
{
    item.ItemDB.somevalue= item.Item.somevalue;
    SaveToDatabase(item.ItemDB);
}

But.... I think the solution you already had, is more readable for everyone.

Create an extension method NullOrEmpty that checks if the collection is null and returns empty:

public static IEnumerable<T> NullOrEmpty<T>(this IEnumerable<T> source)
{
    return source ?? Enumerable.Empty<T>();
}

Then use it:

foreach (var item in items.NullOrEmpty())
{
   ...
}

This is a reasonable solution, there isn't much to be changed. I would only change the first if around to prevent nesting:

private void CheckForNewItems()
{
    var items = GetChangedItems();
    if (items == null)
    {
        return;
    }
    foreach (var item in items )
    {
        var itemDB= GetItem(item.id);
        if (itemDB!=null)
        {
            itemDB.somevalue= item.somevalue;
            SaveToDatabase(itemDB);
        }
    }
}

You could use Null propagation. But then your SaveToDatabase Method would have to check for Null itself. It could also use Null propagation

private void CheckForNewItems()
    {
        var items = GetChangedItems();
        if (items != null)
        {
            foreach (var item in items )
            {
                var itemDB= GetItem(item.id);
                itemDB?.somevalue= item.somevalue;
                SaveToDatabase(itemDB);                   
            }
        }
    }

Have a look at : https://roslyn.codeplex.com/discussions/540883

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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