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

2019-08-08 16:59发布

问题:

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 "" ?

回答1:

this should do it

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


回答2:

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"
} );


标签: c# list lambda