Reputation: 3930
I have a List<>
of abstract objects that contains different types of objects.
I am trying to grab all the items of a certain type and set those items to their own List<>
.
This is not working -
//myAbstractItems is a List<myAbstractItem>
//typeAList inherents from myAbstractItem
var typeAList = ((List<itemTypeA>)myAbstractItems.Where(i => i.GetType() == typeof(itemTypeA)).ToList());
The casting (List<itemTypeA>)
appears to be failing.
Upvotes: 6
Views: 2543
Reputation: 867
This will work for all itemTypeA
s (and more derived types).
var typeAList = myAbstractItems.Select(i => i as itemTypeA).Where(i => i != null).ToList();
EDIT: edited as per Rawling's comment.
Upvotes: 0
Reputation: 71573
Another way you could do this is using the OfType() method:
var typeAList = myAbstractItems.OfType<itemTypeA>().ToList();
This method basically performs the following operation:
var typeAList = myAbstractItems.Where(i=>i is itemTypeA).Select(i=>i as itemTypeA).ToList();
Keep in mind that this will fail if any element of the source collection is a null reference.
Upvotes: 0
Reputation: 30097
Try using Where
this way:
var typeAList = myAbstractItems.Where(i => i.GetType() == typeof(itemTypeA)).Select(item => item as itemTypeA).ToList())
Upvotes: 0
Reputation: 16612
Use the OfType
extension method:
var typeAList = myAbstractItems.OfType<itemTypeA>().ToList();
From the documentation...
The OfType(IEnumerable) method returns only those elements in source that can be cast to type TResult.
Upvotes: 13
Reputation: 4065
A good old loop should be fine :
List<itemTypeA> res = new List<itemTypeA>();
foreach(var item in myAbstractItems)
{
itemTypeA temp = item as itemTypeA;
if (temp != null)
res.Add(temp)
}
Upvotes: 0