Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting object to List<object>

Tags:

c#

object

list

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
    }
}
like image 900
BillP3rd Avatar asked Mar 02 '26 03:03

BillP3rd


1 Answers

Try This:

list = (listObject as IEnumerable).Cast<object>().ToList()
like image 155
dmck Avatar answered Mar 04 '26 17:03

dmck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!