The World’s Leading Microsoft .NET Magazine
   
 
timstall

Donate Today!

Search Box

 

Calendar

««Feb 2010»»
SMTWTFS
 
1
23456
78910111213
14151617181920
21222324252627
28

My RSS Feeds








Mailing List

Most Popular Tags

                                                           

Converting a List to an Array and back using Generics

posted Monday, 20 August 2007

UPDATE (8/21/2007): A comment from Martin shows that you can actually do this much simpler, using standard .Net constructors and methods. So, this code snippet is now just an example showing some features of Generics.

 

I love Generics in C# 2.0 because they let you abstract out type, which lets you code at a greater level of reusability. For example, you could use Generics to abstract out return type. You could also use Generics for standard set and conversion operations.

 

Say your code juggles between System.Collections.Generic.List<T> and arrays. Lists are great for adding and removing items; arrays are just ubiquitous. You could easily write a converter utility methods to handle this:

 

    public static List<T> ConvertArrayToList<T>(T[] myArray)
    {
      if (myArray == null)
        return null;

      List<T> myList = new List<T>();

      for (int i = 0; i < myArray.Length; i++)
      {
        myList.Add(myArray[i]);
      }
      return myList;
    }

    public static T[] ConvertListToArray<T>(List<T> myList)
    {
      if (myList == null)
        return null;

      T[] myArray = new T[myList.Count];

      for (int i = 0; i < myArray.Length; i++)
      {
        myArray[i] = myList[i];
      }
      return myArray;
    }

 

Here we use the generic 'T' to abstract out an input value, the return type, and even to create a new object within the method. It's obviously much better than writing custom converter methods for all your object collections, or every using the ArrayList and unboxing.

 

Here's a simple unit test that shows how to call each method. It round-trips between the two - i.e. you should be able to convert from a list to an array and back to a list, and the final list should match the original one.

 

    [TestMethod]
    public void Convert_ListToArrayRoundTrip_1()
    {
      string[] astr = new string[] { "a", "bb", "ccc" };
      List<string> lstr = MyClass.ConvertArrayToList<string>(astr);

      string[] astr2 = MyClass.ConvertListToArray<string>(lstr);

      Assert.AreEqual(astr.Length, astr2.Length);
      Assert.AreEqual(astr[0], astr[0]);
    }

 

Besides convert methods, you could also write simple set methods, like something to remove all the items from a list:

 

    public static List<T> RemoveItems<T>(List<T> mainList, List<T> itemsToRemove)
    {
      if (mainList == null)
        return null;

      if (itemsToRemove == null || itemsToRemove.Count == 0)
        return mainList;

      for (int i = 0; i < itemsToRemove.Count; i++)
      {
        mainList.Remove(itemsToRemove[i]);
      }
      return mainList;
    }

 

You could write a test for the basic case:

 

    [TestMethod]
    public void RemoveItems_Some()
    {
      List<int> iMain = new List<int>();
      iMain.AddRange(new int[] { 10, 20, 30, 40, 50 });

      List<int> iRemove = new List<int>();
      iRemove.AddRange(new int[] { 30, 50, 70 });

      List<int> iFinal = MyClass.RemoveItems<int>(iMain, iRemove);

      Assert.AreEqual(3, iMain.Count);
      Assert.AreEqual(10, iMain[0]);
      Assert.AreEqual(20, iMain[1]);
      Assert.AreEqual(40, iMain[2]);
    }

 

Disclaimer: obviously you could have a lot more unit tests to fully test these methods.

 


Living in Chicago and interested in working for a great company? Check out the careers at Paylocity.

 

tags:    

links: digg this    technorati    




1. Martin left...
Monday, 20 August 2007 4:54 am

You could just use the standard List<T>.ToArray() method and the List<T> constructor can take an array.

public static T[] ConvertListToArray<T>(List<T> myList) { return myList.ToArray(); } public static List<T> ConvertArrayToList<T>(T[] myArray)

  • {

return new List<T>(myArray); }


2. Tim Stall left...
Tuesday, 21 August 2007 3:45 pm

Good point Martin, thanks.


3. Fahim left...
Wednesday, 5 December 2007 3:41 pm

ConvertArrayToList can also be simplified by:

public static List<T> ConvertArrayToList<T>(T[] myArray)

  • {

    • return new List<T>(myArray);

  • }


4. Jordon left...
Friday, 12 September 2008 3:32 pm

Well actually this is useful. And for this reason.

When creating a "BindingList<T>" from an T[] it made it a "Readonly" collection and failed to add items. Nto sure why could be a bug, but I now use this method.

But BindingList<T>.ToArray() is useful.


5. Dave Schinkel left...
Wednesday, 24 June 2009 3:19 pm

Nice post. I was just looking up how to convert a Generic list to an array so that I could pass it into an IEnumerable param.