简体   繁体   中英

Using Linq Select to create a new inherited object

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!

... 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM