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

后端 未结 5 1911
执笔经年
执笔经年 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:21

    This will work for all itemTypeAs (and more derived types).

    var typeAList = myAbstractItems.Select(i => i as itemTypeA).Where(i => i != null).ToList();
    

    EDIT: edited as per Rawling's comment.

    0 讨论(0)
  • 2021-01-29 04:22

    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)
    }
    
    0 讨论(0)
  • 2021-01-29 04:25

    Try using Where this way:

    var typeAList = myAbstractItems.Where(i => i.GetType() == typeof(itemTypeA)).Select(item => item as itemTypeA).ToList())
    
    0 讨论(0)
  • 2021-01-29 04:31

    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.

    0 讨论(0)
  • 2021-01-29 04:33

    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.

    0 讨论(0)
提交回复
热议问题