Using LINQ to Convert an Array Into a Generic List with C#
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!
 
Comments (5) - Posted in ASP.NET 3.5, C#, LINQ  




5 Responses to “Using LINQ to Convert an Array Into a Generic List with C#”

  1. Artem Govorov Says:

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

  2. Peter Says:

    Artem,
    I think I may just be link happy :)

  3. Pau Says:

    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.

  4. Pau Says:

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

  5. simi Says:

    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

Leave a Reply