using LINQ convertAll when some conversions may be null
i have the following code
people = positions.ConvertAll(r=> r.Person).ToList();
but in some cases "Person" is going to be null, in these cases i simply don't want to add them into开发者_如何学Python the converted collection (i dont want null items)
what is the best way of achieving this. Can you have a conditional convertall ??
With LINQ, you can do:
positions.Where(r => r.Person != null)
.Select(r => r.Person)
.ToList();
The ConvertAll
method is not part of LINQ; it's an instance method on List<T>
.
If you want to stick with that, you can do:
positions.FindAll(r => r.Person != null)
.ConvertAll(r => r.Person);
Do note that this is subtly different because the result of the filter and the projection are both List<T>
s, rather than streaming queries. The final result should be the same though.
people = positions
.Where(r => r.Person !=null).ToList()
.ConvertAll(r=> r.Person);
Use Where
to filter out the null occurrences then use Select
:
people = positions.Where(p => p.Person != null).Select(r => r.Person).ToList();
精彩评论