c# – 检查空或空列表

我有一个列表,有时它是空的或是空的.我想要检查它是否包含任何字符串,如果没有,然后添加一个字符串到列表.
var myList = new List<string>(); // I have a list,sometimes it doesn't have any data added to it
if (myList == null) Console.WriteLine("List is never null"); // Expression is always false
if (myList[0] == null) myList.Add("new item"); 
// Index was out of range. Must be non-negative and less than the size of the collection.
// Inner Exception says "null"

解决方法

你需要这个:
if(myList.Count == 0){
    // nothing is there. Add here
}

基本上新的List< T>不会为空,但不会有元素.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...