Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert an array of object to a list of a class

I have an array of objects like:

object[]

All elements of the array if compatible with a type, that I will call

MyClass

How can I convert this object[] to a List ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use LINQ’s Cast and OfType methods, depending on what you want to happen if your array contains an element that is not of type MyClass.

If you want to throw an exception upon encountering an invalid element, use:

var myList = myArray.Cast<MyClass>().ToList();

If you want to silently ignore all items that are not MyClass, use:

var myList = myArray.OfType<MyClass>().ToList();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading