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?
Thanks
List.Remove appears to already support this behavior: pass a null
as the parameter, and it should remove nothing.
To avoid an exception when your .Where
call returns no matches, use FirstOrDefault()
instead of First()
.
Note that if you expect only one item to match the Where
predicate, you should use SingleOrDefault
rather than 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. Are you instead trying to remove all matching JobPhases? If so, you should explore a different approach, such as using 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"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.