Get all items of a certain type from a List of abstract type

后端 未结 5 1956
执笔经年
执笔经年 2021-01-29 03:27

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

5条回答
  •  半阙折子戏
    2021-01-29 04:31

    Another way you could do this is using the OfType() method:

    var typeAList = myAbstractItems.OfType().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.

提交回复
热议问题