Casting a list of objects to another one

73 views Asked by At

I have the following classes(entities): Entity(base class, has 3 props) & Category(derives from Entity and adds some other props)

The problem occurs when I read data from the DB(the fill method returns a list of Entities) and the compiler doesn't allow me to cast from Entity to Category.

The problematic code:

var categories = (Category)categoryDao.Read();

I can do the process in a very different way though:

var categories = new List<Category>();
foreach (var item in categoryDao.Read())
{
    categories.Add((Category)item);
}

But it's probably bad and unnecessary. So, the question is, can I do this in a more simple way using LINQ + LAMBDA, or there are other tricks?

1

There are 1 answers

0
Glorfindel On BEST ANSWER

The return type of Read() is probably something like IEnumerable<Entity> or List<Entity>. That's why you can't cast them to a single Category.

If you need a one line solution for this, you could try

var categories = categoryDao.Read().OfType<Category>();

or (thanks @Binkan Salaryman)

var categories = categoryDao.Read().Cast<Category>();

(the former will return only the elements which are of type Category - the latter will throw an exception if there are elements which cannot be cast into Category)