检查空或空的List< string> [英] Checking for empty or null List<string>
问题描述
我有一个列表,其中有时为空或为null.我希望能够检查它是否包含任何列表项,如果不包含,则将一个对象添加到列表中.
I have a List where sometimes it is empty or null. I want to be able to check if it contains any List-item and if not then add an object to the List.
// I have a list, sometimes it doesn't have any data added to it
var myList = new List<object>();
// Expression is always false
if (myList == null)
Console.WriteLine("List is never null");
if (myList[0] == null)
myList.Add("new item");
//Errors encountered: Index was out of range. Must be non-negative and less than the size of the collection.
// Inner Exception says "null"
推荐答案
尝试以下代码:
if ( (myList!= null) && (!myList.Any()) )
{
// Add new item
myList.Add("new item");
}
后期编辑,因为对于这些检查,我现在想使用以下解决方案. 首先,添加一个称为Safe()的小型可重用扩展方法:
A late EDIT because for these checks I now like to use the following solution. First, add a small reusable extension method called Safe():
public static class IEnumerableExtension
{
public static IEnumerable<T> Safe<T>(this IEnumerable<T> source)
{
if (source == null)
{
yield break;
}
foreach (var item in source)
{
yield return item;
}
}
}
然后,您可以像执行以下操作:
And then, you can do the same like:
if (!myList.Safe().Any())
{
// Add new item
myList.Add("new item");
}
我个人觉得这不太冗长,更易于阅读.现在,您可以安全地访问任何集合,而无需进行空检查.
I personally find this less verbose and easier to read. You can now safely access any collection without the need for a null check.
然后使用另一个编辑? (空条件)运算符(C#6.0):
And another EDIT, using ? (Null-conditional) operator (C# 6.0):
if (!myList?.Any() ?? false)
{
// Add new item
myList.Add("new item");
}
这篇关于检查空或空的List< string>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!