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?
The return type of
Read()
is probably something likeIEnumerable<Entity>
orList<Entity>
. That's why you can't cast them to a singleCategory
.If you need a one line solution for this, you could try
or (thanks @Binkan Salaryman)
(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 intoCategory
)