简体   繁体   English

C#LINQ可以为空。内联空值检查

[英]C# LINQ nullable .Where inline null check

I am attempting to do the following 我试图做以下事情

List<JobPhase> jobPhases = new JobPhaseDao().findAll();
jobPhases.Remove(jobPhases.Where(m => m.Name.Contains("Pre")).First());

Is there an elegant way to do an inline null check here such that if the list find any matches I can remove nothing? 有没有一种优雅的方法在这里进行内联null检查,如果列表找到任何匹配我可以删除任何内容?

Thanks 谢谢

List.Remove appears to already support this behavior: pass a null as the parameter, and it should remove nothing. List.Remove似乎已经支持此行为:传递null作为参数,它应该不删除任何内容。

To avoid an exception when your .Where call returns no matches, use FirstOrDefault() instead of First() . 要避免在.Where调用返回不匹配时发生异常,请使用FirstOrDefault()而不是First()

Note that if you expect only one item to match the Where predicate, you should use SingleOrDefault rather than First . 请注意,如果您只希望一个项与Where谓词匹配,则应使用SingleOrDefault而不是First

That said, it's not entirely clear what you're trying to do: if you have multiple JobPhases that contain "Pre" in the name, you are somewhat-arbitrarily removing one of them from the list. 也就是说,你要做的事情并不完全清楚:如果你的名字中有多个包含“Pre”的JobPhases,你有点随意从列表中删除其中一个。 Are you instead trying to remove all matching JobPhases? 您是否尝试删除所有匹配的JobPhases? If so, you should explore a different approach, such as using RemoveAll() . 如果是这样,您应该探索不同的方法,例如使用RemoveAll() For example: 例如:

List<JobPhase> jobPhases = new JobPhaseDao().findAll();
jobPhases.RemoveAll(jobPhases.Where(m => m.Name.Contains("Pre")));
List<JobPhase> jobPhases = new JobPhaseDao().findAll()
    .Where(m => !m.Name.Contains("Pre"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM