0

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 ?

Beetlejuice
  • 4,292
  • 10
  • 58
  • 84
  • 1
    `yourArray.Cast().ToList()`, if all objects in the `object[]` are `MyClass` instances, or `yourArray.OfType().ToList()` if the `object[]` is heterogenous and you want to select `MyClass` instances. – Johnathan Barclay May 25 '22 at 12:11
  • @JohnathanBarclay, that is it. Perfectly. – Beetlejuice May 25 '22 at 12:14
  • Does this answer your question? [C# Cast Entire Array?](https://stackoverflow.com/questions/2068120/c-sharp-cast-entire-array) – Orace May 25 '22 at 12:17

2 Answers2

4

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();
Heinzi
  • 167,459
  • 57
  • 363
  • 519
1

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{
    
}
Zagatho
  • 523
  • 1
  • 6
  • 22