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

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!

 
About Peter Kellner

Peter is a software professional specializing in mobile and web technologies. He has also been a Microsoft MVP since 2007. In addition, he's a multi-course video author at Pluralsight. To read more about Peter Kellner and his experience click here. For information about how Peter Kellner might be able to help you with your project click here.

Follow me:


Comments

  1. Gicu Pruneanu says:

    Hi Peter,

    I was wondering to know which collection of objects performs better? cmRateResult[] or List?

    Thanks,
    Gicu

  2. 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

  3. Erm, yeah that should have come out as:
    List<cmRateResult> recs = new List<cmRateResult>(cmRateResults);

  4. 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.

  5. Artem,
    I think I may just be link happy 🙂

  6. Artem Govorov says:

    Not sure why you even need Select, this would work for you: cmRateResults.ToList()

Follow

Get every new post delivered to your Inbox

Join other followers: