You can use LINQ:
lstPlaces = res.Results.Select(x => new PlaceInfo(x)).ToList();
remember to add using System.Linq
at the top of the file.
문제
I have a class PlaceInfo
that contains a private field of type Result
. in the constructor of PlaceInfo
i take parameter of type Result
.
Now my JsonConvert.DeserializeObject<SearchFind>(JsonData);
statement provides me Result[]
in res.Results
.
I have to construct a List<PlaceInfo>
.
The simplest and thumb logical way is given below (that i am using currently).
foreach (var serverPlace in res.Results)
lstPlaces.Add(new PlaceInfo(serverPlace));
Can anyone suggest me advanced constructs?
해결책
You can use LINQ:
lstPlaces = res.Results.Select(x => new PlaceInfo(x)).ToList();
remember to add using System.Linq
at the top of the file.
다른 팁
You could use the Linq Select and ToList method
Result[] results = ...
List<PlaceInfo> places = results.Select(x => new PlaceInfo(x)).ToList();
The Select
method is a projection, applying the given function to all the elements in your array. The ToList
method takes the resultant IEnumerable
and creates a List
.