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 ?
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 ?
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();
You can use Linq to achieve this:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
object[] l = new object[3];
l[0] = new MyClass();
l[1] = new MyClass();
l[2] = new NotMyClass();
var res = l.Where(e => e is MyClass).Cast<MyClass>();
foreach(var e in res){
Console.WriteLine(e.ToString());
}
}
}
public class MyClass{
}
public class NotMyClass{
}