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 th
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.
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)
}
Try using Where
this way:
var typeAList = myAbstractItems.Where(i => i.GetType() == typeof(itemTypeA)).Select(item => item as itemTypeA).ToList())
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.
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.