tags:

views:

101

answers:

3

I have a class with these properties:

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

CapitalCallCommitmentItem inherits CommitmentItem. I want the CapitalCallCommitmentItems property to return all CommitmentItems where the type is of 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 saying:

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

What's the right way to do this?

+10  A: 

Use the OfType extension method.

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

In your code, although you're filtering on the subtype in the where clause, it is still going to return the general type of the list. OfType will return an enumerable of the provided type.

Anthony Pegram
+2  A: 

be sure that it is convertible/castable/oftype.

then try eg
.Cast<T>()
.OfType<T>()

Andreas Niedermair
For OfType it doesn't even has to be castable.
Dykam
i know, but sort of... it should rather state "of type" :)
Andreas Niedermair
A: 

You're on to it. The following works fine at my machine. The resulting list will be of type List<CapitalCallCommitmentItem>:

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

Update: ...but yeah, CommitmentItems.OfType<CapitalCallCommitmentItem> is superior.

Peter Lillevold