Home > Back-end >  Convert an array of object to a list of a class
Convert an array of object to a list of a class

Time:05-25

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 ?

CodePudding user response:

You can use Linq to achive 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{
    
}

CodePudding user response:

It depends on what you want to happen if your array contains an element that is not of type MyClass.

If you want that case to throw an exception, 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();
  •  Tags:  
  • c#
  • Related