3

I've looked at similar questions but nothing quite fits. I have an object which happens to contain a List. I'd like to get it into something I can enumerate.

For example:

object listObject;          // contains a List<Something>
List<object> list;

list = listObject as List<object>;   // list contains null after

foreach ( object o in list )
{
    // do stuff
}

The conversion from object to List<object> is the problem.

EDIT:

What I finished with:

object listObject;          // contains a List<Something>
List<object> list;

IEnumerable enumerable = listObject as IEnumerable;

if ( enumerable != null )
{
    list = enumerable.Cast<object>().ToList();

    foreach ( object o in list )
    {
         // do stuff
    }
}
0

1 Answer 1

7

Try This:

list = (listObject as IEnumerable).Cast<object>().ToList()
Sign up to request clarification or add additional context in comments.

4 Comments

The expression (listObject as IEnumerable).Cast<object>() will throw a NullReferenceException if listObject is cannot be cast to IEnumerable. The expression ((IEnumerable)listObject).Cast<object>() provides a slightly more informative exception if listObject is non-null and does not implement IEnumerable.
@Corey - I was just waiting the required 10 minutes to Accept.
@280Z28 - I understand At this point in my code, I'm guaranteed that it'll be a List of something.
@BillP3rd Sorry. I see a lot of good elegant answers that never get credited is all :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.