Skip to content

Using LINQ to Convert an Array Into a Generic List with C#

Updated: at 02:12 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!

 
Check out the ORM (Object Relational Mapper) PRISMA. The database access method I use in all my projects