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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我写了很多类似上面代码的代码.在这种情况下,是否有更智能的方法来检查空值?"if(item!= null)"是否有效?我甚至要检查空值吗?
问候
你可以用一些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);
}
Run Code Online (Sandbox Code Playgroud)
但是......我认为你已经拥有的解决方案对每个人来说都更具可读性.
| 归档时间: |
|
| 查看次数: |
576 次 |
| 最近记录: |