tags:

views:

74

answers:

1

One of the data structures in my current project requires that I store lists of various types (String, int, float, etc.). I need to be able to dynamically store any number of lists without knowing what types they'll be.

I tried storing each list as an object, but I ran into problems trying to cast back into the appropriate type (it kept recognizing everything as a List<String>).

For example:

List<object> myLists = new List<object>();

public static void Main(string args[])
{
    // Create some lists...

    // Populate the lists...

    // Add the lists to myLists...

    for (int i = 0; i < myLists.Count; i++)
    {
        Console.WriteLine("{0} elements in list {1}", GetNumElements(i), i);
    }
}

public int GetNumElements(int index)
{
    object o = myLists[index];

    if (o is List<int>)
        return (o as List<int>).Count;

    if (o is List<String>)                  // <-- Always true!?
        return (o as List<String>).Count;   // <-- Returning 0 for non-String Lists

    return -1;
}

Am I doing something incorrectly? Is there a better way to store a list of lists of various types, or is there a better way to determine if something is a list of a certain type?

+6  A: 

The type List<T> inherits from the non-generic interface IList. Since all of the values in the myList type are bound intsance of List<T> you can use them as the non-generic IList. So you can use that to greatly simplify your logic

public int GetNumElements(int index) {
  object o = myLists[index];
  var l = o as IList;
  return l.Count;
}

Or alternatively since you know that all of the values stored in myList will be a bound version of List<T>, use IList as the type instead of object.

List<IList> myLists = new List<IList>();
...
public int GetNumElements(int index) {
  return myList[index].Count;
}
JaredPar
This works until I have to do any manipulation to the lists, or when I have to retrieve an element from the list after it's been inserted into the master list.Is there any easy way to tell what Type an `IList` is?
themarshal
@themarshal no not really. The only way to really check is to use the 'as' operator to cast to the supported types and manipulate them
JaredPar
I finally figured a way to keep track of the type of list as it was being inserted. The reason everything kept getting read as a String list was because when I was creating the lists based on type, the "Integer" type was mistakenly generating a List<String>. Oops!
themarshal