如何检查List()是空的 [英] How to check List() is empty

查看:65
本文介绍了如何检查List()是空的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我有

 s =  new 列表< string> ;()



返回

   

当我使用断点时



现在我似乎无法验证

   s 

使用

  null  





例如

  if (result.s ==  null 
{
errorText = 错误
}
否则
{
// 在这里播放刽子手代码
}





它总是跳过if并跳转到else ...

解决方案
当你声明一个引用类型,它是null ...直到你初始化它。



所以当你声明:List< string> S; //是空的



而且,当你初始化的时候:s = new List< string>(); //不是null,内部列表有#0元素。



您可以检查'null和内部列表的情况,其中#0元素是这样的:

  if (s ==  null  || s.Count ==  0 
{
errorText = 错误;
}
其他
{
// < span class =code-comment> playHangman(?,?...?);

}

此代码利用了在运行时.NET的事实将评估第一个逻辑术语在'if语句或测试并返回'如果它评估为'true 而不评估OR测试的第二个术语,则为真。



如果您在声明但未初始化时尝试访问's的Count属性,则会导致错误。



但是,如果您确定已经初始化了,那么您可以使用(s.Count == 0)作为您的测试表达式。


如果您在它之前检查s的值正在初始化,它将为null。由于使用s = new List< string>()来实例化S,因此它不能为空。



如果你想知道s中是否有值,你可以直接检查s.count()。如果值为0,则表示其中没有值。


if(s.count()== 0

{



}

其他

{

}


Hi

I have

s=new List<string>()


that returns

""

when am using a breakpoint

Now I cant seem to validate

"s"

using

null



eg

 if(result.s==null)
{
errorText="error"
}
else
{
//Play hangman code here
}



It always skip the if and jumps to else...

解决方案

When you declare a Reference Type, it is null ... until you initialize it.

So when you declare: List<string> s; // 's is null

And, when you intialize 's: s = new List<string>(); // 's is not null, internal List has #0 elements.

You can check for both the case of 'null and internal List having #0 elements like this:

if (s == null || s.Count == 0)
 {
     errorText = "error";
 }
 else
 {
     // playHangman(?, ? ... ?);
 }

This code takes advantage of the fact that at run-time .NET will evaluate the first logical term in an 'if statement OR test and return 'true if it evaluates to 'true without evaluating the second term of the OR test.

If you tried to access the Count Property of 's when it was declared, but not initialized, that would cause an error.

However, if you are certain you have initialized 's, then you can just use (s.Count == 0) for your test expression.


If you check for the value of s before it is being initialized, it will be null. Since "S" is instantiated using s=new List<string>(), it can't be null.

If you want to know if s has values in it you can simply check for s.count(). If the value is 0, it means there are no values in it.


if(s.count()==0
{

}
else
{
}


这篇关于如何检查List()是空的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆