检查空或空列表<字符串>
本文关键字:字符串 列表 检查 | 更新日期: 2023-09-27 18:10:16
>我有一个列表,有时它是空的或空的。我希望能够检查它是否包含任何列表项,如果没有,则将对象添加到列表中。
// 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(( 的小型可重用扩展方法:
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;
}
}
}
然后,您可以像这样做同样的事情:
if (!myList.Safe().Any())
{
// Add new item
myList.Add("new item");
}
我个人觉得这不那么冗长,更容易阅读。现在可以安全地访问任何集合,而无需进行空检查。
另一个 EDIT,它不需要扩展方法,但使用 ?(空条件(运算符 (C# 6.0(:
if (!(myList?.Any() ?? false))
{
// Add new item
myList.Add("new item");
}
对于无法保证列表不会为 null 的任何人,您可以使用 null 条件运算符在单个条件语句中安全地检查 null 和空列表:
if (list?.Any() != true)
{
// Handle null or empty list
}
查看 L-Four 的答案。
效率较低的答案:
if(myList.Count == 0){
// nothing is there. Add here
}
基本上new List<T>
不会null
,但不会有任何元素。 如注释中所述,如果列表未实例化,上述内容将引发异常。但是对于问题中的片段,它被实例化的地方,上面的工作就可以了。
如果您需要检查空,那么它将是:
if(myList != null && myList.Count == 0){
// The list is empty. Add something here
}
更好的是使用!myList.Any()
,正如前面提到的L-Four的答案中提到的,短路比列表中元素的线性计数更快。
使用扩展方法怎么样?
public static bool AnyOrNotNull<T>(this IEnumerable<T> source)
{
if (source != null && source.Any())
return true;
else
return false;
}
组合myList == null || myList.Count == 0
的一种简单方法是使用 null 合并运算符 ??
:
if ((myList?.Count ?? 0) == 0) {
//My list is null or empty
}
if (myList?.Any() == true)
{
...
}
我发现这是最方便的方式。'== true' 检查 '?' 隐含的可为空布尔值的值。Any((
我想知道没有人建议为 OP 的情况创建自己的扩展方法更易读的名称。
public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
{
if (source == null)
{
return true;
}
return source.Any() == false;
}
假设列表从不为 null,以下代码将检查列表是否为空,如果为空,则添加一个新元素:
if (!myList.Any())
{
myList.Add("new item");
}
如果列表可能为 null,则必须在Any()
条件之前添加 null 检查:
if (myList != null && !myList.Any())
{
myList.Add("new item");
}
在我看来,使用 Any()
而不是 Count == 0
更可取,因为它更好地表达了检查列表是否有任何元素或为空的意图。但是,考虑到每种方法的性能,使用Any()
通常比Count
慢。
IsNullOrEmpty()
扩展方法是一种非常优雅且人类可读的实现方式,所以我决定使用它。但是,您也可以在没有扩展方法的情况下实现相同的目标。
假设我们有一个名为 list
的对象,类型为 List<T>
(例如 List<string>
(。如果你想知道列表是否有项目,你可以说:
list?.Count > 0 // List<T> has items
这将返回空列表的false
,如果列表本身是null
对象,true
否则。
因此,如果要检查列表是否没有任何项目,您唯一需要做的就是反转上述表达式:
!(list?.Count > 0) // List<T> is null or empty
这将返回空列表的true
,如果列表本身是null
对象,否则false
返回。这正是您对IsNullOrEmpty
评估的期望。只是有点神秘!
当List<T>
实现IEnumerable<T>
时,你可以实现同样的事情,而不是那么具体,但这可能会导致评估变慢:
list?.Any() != true // IEnumerable<T> is null or empty
您的列表没有项目,这就是为什么访问不存在的第 0 个项目的原因
myList[0] == null
抛出索引超出范围异常;当您要访问第 n 项时检查
if (myList.Count > n)
DoSomething(myList[n])
在您的情况下
if (myList.Count > 0) // <- You can safely get 0-th item
if (myList[0] == null)
myList.Add("new item");
myList[0]
获取列表中的第一项。 由于列表为空,因此没有要获取的项目,而是获取IndexOutOfRangeException
。
正如此处的其他答案所示,为了检查列表是否为空,您需要获取列表中的元素数(myList.Count
(或使用 LINQ 方法.Any()
如果列表中有任何元素,该方法将返回 true。
这里的大多数答案都集中在如何检查集合是空的还是空的,正如他们所展示的那样,这非常简单。
像这里的许多人一样,我也想知道为什么Microsoft本身不提供已经为字符串类型(String.IsNullOrEmpty()
(提供的这样一个基本功能?然后我从Microsoft遇到了这个指南,它说:
X 不从集合属性或返回集合的方法返回 NULL 值。改为返回空集合或空数组。
一般规则是空和空(0 项(集合或数组 应一视同仁。
因此,理想情况下,如果您遵循 Microsoft 中的此准则,则永远不应该有一个 null 的集合。这将帮助您删除不必要的空检查,最终使您的代码更具可读性。在这种情况下,有人只需要检查:myList.Any()
找出列表中是否存在任何元素。
希望这个解释能帮助那些将来会遇到同样问题的人,并想知道为什么没有任何这样的功能来检查集合是空还是空。
多种方式检查列表是否为空
1(清单为空,然后检查计数大于零,如下所示:-
if (myList != null && myList.Count > 0)
{
//List has more than one record.
}
2(使用 LINQ 查询检查清单 null 和计数大于零,如下所示:-
if (myList?.Any() == true)
{
//List has more than one record.
}
public static bool IsNullOrEmpty<T>(this IEnumerable<T> items)
{
return !(items?.Any() ?? false);
}
此扩展方法可帮助您确定列表是 null 还是空。它可以按如下方式使用:
using System;
using System.Linq;
using System.Collections.Generic;
public static class IEnumerableExtensions
{
public static bool IsNullOrEmpty<T>(this IEnumerable<T> items)
{
return !(items?.Any() ?? false);
}
}
public class Program
{
public static void Main()
{
List<string> test1 = null;;
Console.WriteLine($"List 1 is empty: {test1.IsNullOrEmpty()}");
//Output: List 1 is empty: True
var test2 = new System.Collections.Generic.List<string>();
System.Console.WriteLine($"List 2 is empty: {test2.IsNullOrEmpty()}");
//Output: List 2 is empty: True
var test3 = new System.Collections.Generic.List<string>();
test3.Add("test");
System.Console.WriteLine($"List 3 is empty: {test3.IsNullOrEmpty()}");
//Output: List 3 is empty: False
}
}
c#
中的List
具有Count
属性。 它可以像这样使用:
if(myList == null) // Checks if list is null
// Wasn't initialized
else if(myList.Count == 0) // Checks if the list is empty
myList.Add("new item");
else // List is valid and has something in it
// You could access the element in the list if you wanted
如果你想要一个同时检查空和空的单行条件,你可以使用
if (list == null ? true : (!list.Any()))
这将适用于 null 条件运算符不可用的旧框架版本。
尝试使用:
if(myList.Any())
{
}
注意:这个assmumes myList不为空。
您可以在 c# 中使用 List 的 Count 属性
请在下面的代码中找到检查在单个条件中列出空和空
if(myList == null || myList.Count == 0)
{
//Do Something
}
我们可以使用扩展方法进行如下验证。我将它们用于我的所有项目。
var myList = new List<string>();
if(!myList.HasValue())
{
Console.WriteLine("List has value(s)");
}
if(!myList.HasValue())
{
Console.WriteLine("List is either null or empty");
}
if(myList.HasValue())
{
if (!myList[0].HasValue())
{
myList.Add("new item");
}
}
/// <summary>
/// This Method will return True if List is Not Null and it's items count>0
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <returns>Bool</returns>
public static bool HasValue<T>(this IEnumerable<T> items)
{
if (items != null)
{
if (items.Count() > 0)
{
return true;
}
}
return false;
}
/// <summary>
/// This Method will return True if List is Not Null and it's items count>0
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <returns></returns>
public static bool HasValue<T>(this List<T> items)
{
if (items != null)
{
if (items.Count() > 0)
{
return true;
}
}
return false;
}
/// <summary>
/// This method returns true if string not null and not empty
/// </summary>
/// <param name="ObjectValue"></param>
/// <returns>bool</returns>
public static bool HasValue(this string ObjectValue)
{
if (ObjectValue != null)
{
if ((!string.IsNullOrEmpty(ObjectValue)) && (!string.IsNullOrWhiteSpace(ObjectValue)))
{
return true;
}
}
return false;
}
我们可以添加一个扩展名来创建空列表
public static IEnumerable<T> Nullable<T>(this IEnumerable<T> obj)
{
if (obj == null)
return new List<T>();
else
return obj;
}
并像这样使用
foreach (model in models.Nullable())
{
....
}
我个人为IEnumerable类创建了一个扩展方法,我称之为IsNullOrEmpty((。因为它适用于IEnumerable的所有实现,所以它适用于List,也适用于String,IReadOnlyList等。
我的实现很简单:
public static class ExtensionMethods
{
public static bool IsNullOrEmpty(this IEnumerable enumerable)
{
if (enumerable is null) return true;
foreach (var element in enumerable)
{
//If we make it here, it means there are elements, and we return false
return false;
}
return true;
}
}
然后,我可以在列表中使用该方法,如下所示:
var myList = new List<object>();
if (myList.IsNullOrEmpty())
{
//Do stuff
}
<</div>
div class="answers"> 我只是想在这里添加一个答案,因为这是 Google 上检查列表是空还是空的热门歌曲。对我来说,.Any
是不被承认的。如果您想在不创建扩展方法的情况下进行检查,您可以像这样操作,这非常简单:
//Check that list is NOT null or empty.
if (myList != null && myList.Count > 0)
{
//then proceed to do something, no issues here.
}
//Check if list is null or empty.
if (myList == null || myList.Count == 0)
{
//error handling here for null or empty list
}
//checking with if/else-if/else
if (myList == null)
{
//null handling
}
else if(myList.Count == 0)
{
//handle zero count
}
else
{
//no issues here, proceed
}
如果列表可能为 null,那么您必须首先检查 null - 如果您尝试先检查计数并且列表恰好为 null,那么它将抛出错误。 &&
和||
是短路运算符,因此只有在不满足第一个条件时才评估第二个条件。
您可以添加此 IEnumerable 扩展方法,如果源序列包含任何元素且不为 null,则返回 true。否则返回 false。
public static class IEnumerableExtensions
{
public static bool IsNotNullNorEmpty<T>(this IEnumerable<T> source)
=> source?.Any() ?? false;
}
因为您使用"new"初始化 myList,所以列表本身永远不会为空。
但它可以用"空"值填充。
在这种情况下,.Count > 0
和.Any()
都是真的。您可以使用.All(s => s == null)
进行检查
var myList = new List<object>();
if (myList.Any() || myList.All(s => s == null))
这能够解决您的问题'如果(列表。长度> 0({
}'