当某些转换可能为null时,使用LINQ convertAll

leo*_*ora 1 c# linq

我有以下代码

          people = positions.ConvertAll(r=> r.Person).ToList();
Run Code Online (Sandbox Code Playgroud)

但在某些情况下,"Person"将为null,在这些情况下我根本不想将它们添加到已转换的集合中(我不想要空项)

实现这一目标的最佳方式是什么?你有条件转换?

Ani*_*Ani 6

使用LINQ,您可以:

positions.Where(r => r.Person != null)
         .Select(r => r.Person)
         .ToList();
Run Code Online (Sandbox Code Playgroud)

ConvertAll方法不是LINQ的一部分; 它是一个实例方法List<T>.如果你想坚持下去,你可以这样做:

positions.FindAll(r => r.Person != null)
         .ConvertAll(r => r.Person);
Run Code Online (Sandbox Code Playgroud)

请注意,这是微妙的不同,因为过滤器投影的结果都是List<T>s,而不是流式查询.最终结果应该是相同的.