C# 如何确定是否存在';列表项C上的值为空#

C# 如何确定是否存在';列表项C上的值为空#,c#,.net,xamarin,nullable,C#,.net,Xamarin,Nullable,一个简短的问题 如何确定我的整个列表项是否有空值(例如,此项) 请注意,我的列表是动态的,所以我不能像手动获取代码中的 我就是这样得到这份名单的 item.BList.Add(AllList.Where(x => x.Id == id).FirstOrDefault()); 到目前为止我试过的是这个 if(items.SelectedItem== null) { item.BList.Add(AllList.Where(x => x.Id == id).FirstOr

一个简短的问题

如何确定我的整个列表项是否有空值(例如,此项)

请注意,我的列表是动态的,所以我不能像手动获取代码中的

我就是这样得到这份名单的

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;
}


但不会删除,而是会使我的应用程序崩溃

以删除您只需执行以下操作的所有内容

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;
}
您可以使用带有否定的
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()


在遍历列表(foreach)时,不能从列表中删除项,因为它会更改列表的顺序或元素以及长度,因此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)
不匹配,则将
null
添加到
项.BList
,然后要删除该项。你应该首先避免添加它

你可以这样做:

var element = AllList.Where(x => x.Id == id).FirstOrDefault();
if (element != null)
{
    item.BList.Add(element);
}
item.BList.AddRange(AllList.Where(x => x.Id == id).Take(1));
或者,假设
item.BList
是一个
列表
,如下所示:

var element = AllList.Where(x => x.Id == id).FirstOrDefault();
if (element != null)
{
    item.BList.Add(element);
}
item.BList.AddRange(AllList.Where(x => x.Id == id).Take(1));

我添加了更多信息,很抱歉,您需要
。Any
方法-
AllList.Any(x=>x==null)
。先生,您能解释一下吗,因为我是linq的新手。Any会删除我的null项目列表