![](/img/trans.png)
[英]How to ensure/check that List is not null before adding item in C#?
[英]how to determine if there's a null on the list item C#
一个快速的问题
我如何确定我的整个列表项是否具有空值,例如 this item 。
请注意,我的列表是动态的,所以我不能像手动获取代码中的1一样。
这就是我获取列表的方式
item.BList.Add(AllList.Where(x => x.Id == id).FirstOrDefault());
到目前为止我尝试的是这个
if(items.SelectedItem== null)
{
item.BList.Add(AllList.Where(x => x.Id == id).FirstOrDefault());
foreach (var dep in item.Blist)
{
item.Blist.RemoveAll(item => dep == null);
}
return;
}
但不会删除而是使我的应用程序崩溃
您可以使用带有否定的Where()
子句从列表中获取所有非空值。
item.Blist = item.Blist.Where(item => item != null); //Now item.Blist contains all non null elements.
你的代码看起来像,
if(items.SelectedItem== null)
{
item.BList.Add(AllList.Where(x => x.Id == id).FirstOrDefault());
item.Blist = item.Blist.Where(item => item != null);
return;
}
如果您正在寻找检查列表包含任何null
值的解决方案,那么您可以使用Any()
var isNullValueExist = item.Blist.Any(x => x == null); //This will return boolean value based on predicate
对于全部删除您只需要执行以下操作即可。
item.Blist.RemoveAll(item => item == null);
整体看起来像
if(items.SelectedItem== null)
{
item.BList.Add(AllList.Where(x => x.Id == id).FirstOrDefault());
item.Blist.RemoveAll(item => item == null);
return;
}
在遍历列表 (foreach) 时,您无法从列表中删除 Items,因为它会更改列表的顺序或元素和长度,因此 forach 循环无法正确跟踪索引。
如果您尝试从列表中删除空元素
if(items.SelectedItem== null)
{
item.BList.Add(AllList.Where(x => x.Id == id).FirstOrDefault());
item.Blist.RemoveAll(i => i == null); // You donn't have to iterate the list to do this
foreach (var dep in item.Blist)
{
// Do whatever you want with your items or just remove the forach loop altogether
// item.Blist.RemoveAll(item => dep == null); // don't have to do this here
}
return;
}
在我看来,您正在用这一行创建自己的问题:
item.BList.Add(AllList.Where(x => x.Id == id).FirstOrDefault());
如果.Where(x => x.Id == id)
不匹配,那么您item.BList
添加null
- 然后您想要删除它。 您应该首先避免添加它。
你可以这样做:
var element = AllList.Where(x => x.Id == id).FirstOrDefault();
if (element != null)
{
item.BList.Add(element);
}
或者,假设item.BList
是一个List<T>
,如下所示:
item.BList.AddRange(AllList.Where(x => x.Id == id).Take(1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.