Tuesday, April 21, 2009

Converting One Array Type to Another - Hacking with Lambda

Started with this:

private ResponseListing[] PopulateListings
(ListingFindResult[] listings)
{
List newListings = new List();
ResponseListing newListing;

foreach (ListingFindResult listing in listings)
{
newListing = new ResponseListing(listing);
newListings.Add(newListing);
}
return newListings.ToArray();
}


Hacked to this:

private ResponseListing[] PopulateListings
(ListingFindResult[] listings)
{
return Array.ConvertAll(listings, delegate
(ListingServiceProxy.ListingFindResult d)
{ return new ResponseListing(d); });
}


Final hack with lambda function:

return Array.ConvertAll(listings, d => new ResponseListing(d));

For generic list you can do the following:

List<Pnts> myPoints = GetListOfMyPoints();

List<Point> yourPoints = myPoints.ConvertAll<Point>(p => new Point(p));

Note: the constructor of Point has to be able to take and translate Pnts object







public static TOutput[] ConvertAll(TInput[] array, Converter converter);

string[] sa2 = Array.ConvertAll(data, delegate(double d) { return d.ToString(); });

string[] lambdaSA = Array.ConvertAll(data, d => d.ToString());

Credit goes to Patrick Steele's Blog Loops, Conversions and Lambdas and MSDN Array.ConvertAll

No comments: