Jarrich Van de Voorde
Jarrich Van de Voorde

Reputation: 396

Convert a List to a given Type

I have the following List:

public List<EntityBase> PossibleReplacements

I also have a Type

public Type type;

type will contain a certain class type that inherits EntityBase (That's how my app works). Now I need to cast the list PossibleReplacements to a List of type 'type'

Something like this:

List<type> lijst = PossibleReplacements.Cast<type>();

but this gives an error

'ReplacePopupModel.type' is a 'field' but is used like a 'type' 

I have yet to find a working solution for this.

Can anyone help me out?

Thanks.

Upvotes: 2

Views: 117

Answers (3)

cuongle
cuongle

Reputation: 75306

You cannot use Cast since it is not in type-safe at runtime, you just use where to select:

var lijst = PossibleReplacements.Where(t => t.GetType() == type);

Upvotes: 1

Matten
Matten

Reputation: 17631

Not without reflection, and not safe. But you can follow Reed Copseys first hint and check if all entries are assignable to your type and then use the reflected cast method:

var type = ...your type...

var cast = typeof(IEnumerable<>).GetMethod("Cast").MakeGenericMethod(type);
var list = cast.Invoke(PossibleReplacements, null);

The variable list is now object, but has an reference to a list of the right type. As you don't know your actual type, you may have some interface to access the list (cast required).

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564413

You can get the items out that match the type like so:

List<EntityBase> list = PossibleReplacements.Where(e => type.IsAssignableFrom(e.GetType())).ToList();

This list will only contain items that match (or are subclasses of) the specific type you specified in type.

However, you can't cast to the specific List<T> type because this isn't known at compile time.

If you are trying to extract items of a specific type known at compile time, you can just use:

List<TheType> list = PossibleReplacements.OfType<TheType>().ToList();

Upvotes: 1

Related Questions