Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach inherited (sub-class) object in a super-class list

I have a super-class named "ClassA" and two sub-classes "Class1" and "Class2".

I have a list containing objects of "Class1" and "Class2", that list is of type "ClassA".
I want to loop through only the "Class1" objects in the list by doing something like

List<ClassA> AList = new List<ClassA>;
AList.Add(new Class1());
AList.Add(new Class2());

foreach (Class1 c1 in AList)
{
    // Do Something
}

but when I do that, the code throws an exception when it reaches an object that is not of type "Class1".

How can this be done in a simple way without having to check the type of the object in the list and cast it if it's the correct type. like this:

foreach (ClassA cA in AList)
{
    if (cA.GetType() == typeof(Class1))
    {
        // Do Something
    }
}
like image 584
Amr Avatar asked Jun 09 '10 15:06

Amr


1 Answers

Using LINQ:

foreach (Class1 c1 in AList.OfType<Class1>()) { }

Note that if you want to check for a type in a loop, the as and is operators are meant for this. Like:

foreach (ClassA cA in AList) {
  Class1 c1 = cA as Class1;
  if (c1 != null) {
    // do something
  }
}
like image 99
Julien Lebosquain Avatar answered Oct 25 '22 22:10

Julien Lebosquain