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?
Use the
OfTypeextension method.In your code, although you’re filtering on the subtype in the
whereclause, it is still going to return the general type of the list.OfTypewill return an enumerable of the provided type.