Access List inside Object

I have an object that is a List

object myobject; // 

I know that myobject is a

List<double> or List<string>

I need to print something like this;

for (int i = 0; i < myobject.count()+ i++)
{
    string str = myobject[i].toString();
}

But I don't know how to count objects, and acess some myobject[i]

Upvotes: 0

Views: 782

Answers (3)

I.B
I.B

Reputation: 2923

All you need to do is cast it to the list type you're expecting so if you know its gonna be a List of string you do something like this :

List<string> myList = (List<string>)myobject;

for (int i = 0; i < myList.Count(); i++)
{
    string str = myList[i];
}

This is for if you really don't know if the list you're getting is double or string :

List<string> myStringList = new List<string>();
List<double> myDoubleList = new List<double>();

try {

    myStringList = (List<string>)myobject;

    for (int i = 0; i < myStringList.Count(); i++)
    {
        Console.WriteLine(myStringList[i]);
    }
}
catch (InvalidCastException)
{
    myDoubleList = (List<double>)myobject;

    for (int i = 0; i < myDoubleList.Count(); i++)
    {
        Console.WriteLine(myDoubleList[i]);
    }
}  

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

I suggest extracting a generic method:

// think on turning the method into static  
private void PerformList<T>(List<T> list) {
  // try failed
  if (null == list)
    return;

  // foreach (var item in list) {...} may be a better choice 
  for (int i = 0; i < list.Count; ++i) {
    string str = list[i].ToString();

    ...
  }
}

...

object myobject = ...;

// Try double
PerformList(myobject as List<double>);
// Try string
PerformList(myobject as List<string>);

Upvotes: 1

Christos
Christos

Reputation: 53958

Since the type of myobject there isn't any property called Count. You could try something like the following:

var list = myobject as List<int>();
if(list == null)
{
    // The cast failed. 
    // If the method's return type is void change the following to return;
    return null; 
}
for (int i = 0; i < list.Count; i++)
{
    string str = list[i].toString();
}

Upvotes: 1

Related Questions