Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Object to List<MyClass>?

Tags:

c#

I am trying to make a generic method that can accept any object, in which, even the object is List<AnyClass>. Something like:

public static void MyMethod(object _anyObject)
{

}

So in my method it accept the parameter as Object, then I will determine what to do by their type to do

So when I know that's a List type, I want to convert that Object back to List<AnyClass>, iternate each object and their propertie

I tried to do:

List<object> ObjectList = object as List<object>;

But it will return null, because the object originally is List<AnyClass>

Thanks in advance

================

Edit: Sorry, seems like I haven't make it clear, because I simplifed the problem... I means the Object might be:

_anyObject = List<Class1>
_anyObject = Class2
_anyObject = DataSet
_anyObject = AnyClass
_anyObject = List<object>

So say, the user can even put in a List<object>, but each of the object in that list can be different class..That's why I can't use <T>.

The original of my problem is:

public static void MyMethod(List<object> _anyList)
{

}

Then I don't care what they put into the list, even the object in the list contains another object list...

like image 611
King Avatar asked Mar 09 '11 20:03

King


People also ask

How do I convert a list of strings to a list of objects?

Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList);

What can convert object into list in Java?

toList()) can be used to collect Stream elements into a list. We can leverage this to convert object to a list.

How do I create a list of object types?

You could create a list of Object like List<Object> list = new ArrayList<Object>() . As all classes implementation extends implicit or explicit from java. lang. Object class, this list can hold any object, including instances of Employee , Integer , String etc.


2 Answers

It sounds like you should use method overloading instead of type detection. This will also break your single large method up into smaller, more maintanable methods.

public static void MyMethod(List<AnyClass> list)
{
    foreach (var obj in list)
    {
        MyMethod(obj);
    }
}

public static void MyMethod(AnyClass single)
{
    //work with single instance    
}
like image 190
Chris Shouts Avatar answered Oct 13 '22 17:10

Chris Shouts


The generic List class implements the non-generic IList interface, so you can say:

IList objectList = obj as IList;

However, what you're trying to do is generally considered bad practice as it eliminates any semblance of type safety. If you explain in what context you're using this, we might be able to suggest a better alternative, like using a generic method.

like image 29
StriplingWarrior Avatar answered Oct 13 '22 18:10

StriplingWarrior