How do you extract derived types from a general list?

I have a class with these properties:

public List<CommitmentItem<ITransaction, ITransactionItem>> CommitmentItems;
public List<CapitalCallCommitmentItem> CapitalCallCommitmentItems;

CapitalCallCommitmentIteminherits CommitmentItem. I want the property to CapitalCallCommitmentItemsreturn everything CommitmentItemswhere the type is CapitalCallCommitmentItem. So I tried this code:

get
{                
    return CommitmentItems
        .Where(c => c.GetType() == typeof(CapitalCallCommitmentItem))
        .Select(c => (CapitalCallCommitmentItem)c)
        .ToList();
}

However, I get an error message:

Error 1: Cannot convert type 'Models.CommitmentItem' to 'Models.CapitalCallCommitmentItem'

What is the right way to do this?

+3
source share
3 answers

Use the extension method OfType.

return CommitmentItems.OfType<CapitalCallCommitmentItem>().ToList();

In your code, although you are filtering out a subtype in a sentence where, it will still return the general type of the list. OfTypewill return an enumerated type.

+12

, /castable/oftype.

, , . Cast <T> ()
. OfType <T> ()

+2

You are at it. Works fine on my machine. The resulting list will be of the type List<CapitalCallCommitmentItem>:

get
{                
    return CommitmentItems
        .Where(c => c is CapitalCallCommitmentItem)
        .Select(c => c as CapitalCallCommitmentItem)
        .ToList();
}

Update: ... but yes, CommitmentItems.OfType<CapitalCallCommitmentItem>superior.

+1
source

Source: https://habr.com/ru/post/1751210/


All Articles