C#, in List<>.ConvertAll method using lambda ex

2019-08-08 17:16发布

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

Here, myClassList is a List, and for some reason, the items in the List might be null.

How to achieve this using lambda expression: when the object is not null, return the objStr, if it's null, return an empty string "" ?

标签: c# list lambda
2条回答
我只想做你的唯一
2楼-- · 2019-08-08 17:40

this should do it

string[] myTargetArray=myClassList.ConvertAll<string>(xi => xi==null ? string.Empty : xi.objStr).ToArray();
查看更多
forever°为你锁心
3楼-- · 2019-08-08 17:45

When converting lists of Classes, an example of a First list type into a list of Second type:

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"
} );
查看更多
登录 后发表回答