I have made a my own class with its own properties, and added that to a List<ownclass>
. For working reasons, I have to cast that to a List<object>
. On the other hand I have to cast it back (in a later workaround).
How would this look like?
I have made a my own class with its own properties, and added that to a List<ownclass>
. For working reasons, I have to cast that to a List<object>
. On the other hand I have to cast it back (in a later workaround).
How would this look like?
The following code demonstrates the procedure of casting a list of a custom class to a list of objects, casting the list of objects back into a list of the custom class and reading from the final list.
class MyClass
{
public int MyNumber { get; set; }
}
class Program
{
static void Main(string[] args)
{
var myList = new List<MyClass>()
{
new MyClass { MyNumber = 99 },
new MyClass { MyNumber = 123 }
};
var objectList = myList.Cast<object>().ToList();
var myConvertedList = objectList.Cast<MyClass>().ToList();
foreach (int n in myConvertedList.Select(c => c.MyNumber))
Console.WriteLine(n);
Console.ReadLine();
}
}
to cast it to a list of objects:
List<object> objects = ownClassList.Select( o => (object)o).ToList();
to cast it back :
List<ownclass> ownClassList = objects.Select( o=> (ownclass) o).ToList();
edit: you have to import system.linq