c#,在列表<>使用lambda表达式的ConvertAll方法,如何在对象为空时进行筛选

本文关键字:对象 筛选 ConvertAll 列表 使用 lambda 表达式 方法 | 更新日期: 2023-09-27 18:09:27

string[] myTargetArray=myClassList.ConvertAll<string>(xi=>xi.objStr).ToArray();

这里,myClassList是一个List,由于某些原因,List中的项可能为空。

如何使用lambda表达式实现这一点:当对象不为空时,返回objStr,如果它为空,返回空字符串" ?

c#,在列表<>使用lambda表达式的ConvertAll方法,如何在对象为空时进行筛选

应该可以了

string[] myTargetArray=myClassList.ConvertAll<string>(xi => xi==null ? string.Empty : xi.objStr).ToArray();

在将类列表转换为First列表类型为Second类型列表的示例中:

class First
{
    int id;
    string description;
    DateTime creation;
}
class Second
{
    int id;
    string fullInfo;
}
// more code, not interesting
List<First> firstList = new List();
List<Second> secondList;
firstList.AddRange(fictionalData);
secondList = firstList.ConvertAll(item => new Second {
    id = item.id,
    fullInfo = item.description + " " + item.creation.Year"
} );