Reputation: 4513
I have 2 classes, User
and ExtendedUser
. ExtendedUser
inherits from User
and just adds 2 int
fields - Nothing fancy.
I have a list of User
objects - List<User>
and would like to go over the list and create a list of ExtendedUser
objects, where I'd like to just fill fill the missing int
fields.
I thought about using the Select
method of Linq to create the new objects, but it won't copy the User
to ExtendedUser
- so I'll need to recreate those objects, which doesn't make sense for me.
EDIT:
User
is an Entity, where as ExtendedUser
is a custom class inheriting from that entity (but not an entity by itself).
It seems the easiest solution here would be composition, though conceptually - inheritance would have worked better.
Any smart solutions here? :)
Thanks!
Upvotes: 3
Views: 1517
Reputation: 273189
... of Linq to create the new objects, but it won't copy the User to ExtendedUser - so I'll need to recreate those objects, which doesn't make sense for me.
This is not a shortcoming of Linq.
It is a general principal in strongly typed OOP that you cannot simply convert base class objects to derived objects. Such a conversion always involves copying the members and that raises the issue of identity (which clone is the real one?).
In other words, when an object is supposed to be of class B it should never have started life as type A, even if B derives from A. So do revisit your design and overall solution.
When you still think you need this, then what you have is a situation like converting entities to DTOs and vice versa. And you can use the usual tools like AutoMapper.
Upvotes: 4