Wednesday 14 October 2009 @ 5:35 pm
This is just going to be a short post, but I bet it’s something I do a large number of times so I thought I’d blog it. Say you get back from something like a web service an array of objects.
In my case this:
cmRateResult[] cmRateResults = TransiteUtils.MakeRateRequest(_cmRateRequest);
Then, I want to convert that into
List<cmRateResult]
We all know the foreach way of doing it, about 5 lines of code
var cmRateResultsList = new List<cmRateResult>(cmRateResults.Length); foreach (var r in cmRateResults) { cmRateResultsList.Add(r); }
Or, my preferred way is to use the LINQ for syntax as follows:
var recs = (from data in cmRateResults select data).ToList();But, it’s nicer (IMHO) to do it with LINQ chaining, though exactly the same. here it is:
var recs = cmRateResults.Select(data => data)).ToList()
Hope this helps!











October 14th, 2009 at 7:39 pm
Not sure why you even need Select, this would work for you: cmRateResults.ToList()
October 14th, 2009 at 8:52 pm
Artem,
I think I may just be link happy
October 16th, 2009 at 6:11 am
Or you could just do:
List recs = new List(cmRateResults);
Not sure if it’s any less performant than the .ToList(), but it’s 100% more readable than the Linq version.
October 16th, 2009 at 6:12 am
Erm, yeah that should have come out as:
List<cmRateResult> recs = new List<cmRateResult>(cmRateResults);
December 29th, 2009 at 11:51 pm
hi,
First of all. Thanks very much for your useful post.
I just came across your blog and wanted to drop you a note telling you how impressed I was with the information you have posted here.
Please let me introduce you some info related to this post and I hope that it is useful for .Net community.
There is a good C# resource site, Have alook
http://csharptalk.com
simi