6

So I have a List of BaseClass and I've filled it with several instances of derived classes (only one of each derived class) so that we have something like:

List<BaseClass> myList = new List<BaseClass>();

myList.Add(new DerivedClassA());
myList.Add(new DerivedClassB());
myList.Add(new DerivedClassC());

Now I want to be able to search myList with something like this:

public void FindClass (BaseClass class){ //class is a derived class
   //find index or object of type class
   //so that if class is a DerivedClassB
   //we return the first DerivedClassB in myList 
}

Is this possible? I know I can give each DerivedClass a name property and find it by it's name but I don't want to have to do that.

3
  • 1
    You could use is keyword to determine if it is of derived type.
    – Ian
    Jan 11, 2016 at 7:42
  • 3
    Do you really want FindClass to require an instance to be passed as a parameter? Would a Type not be more suitable here? (Either as a plain parameter or as a generic type parameter) Jan 11, 2016 at 7:42
  • Be aware that, although Domysee's answer is a bit faster than 3dd's solution (see this .NET fiddle) it's less robust against changes. When you subtype from DerivedClass* and add instances of this sub-subtype to the list, then GetType() wont traverse the inheritance hierarchie like the is operator (resp. OfType<T>()) does. Jan 14, 2016 at 10:00

3 Answers 3

6

Another solution would be to use 'OfType<>' to filter the list

public class Base { }

public class DerivedA : Base { }
public class DerivedB : Base { }

List<Base> instances = new List<Base>();
instances.Add(new DerivedA());
instances.Add(new DerivedB());

 var results = instances.OfType<DerivedA>().FirstOrDefault();

EDIT - This is a way of creating a method that would do the search

T Find<T>() where T : Base {
    return _Instances.OfType<T>().FirstOrDefault();
}
2
  • Is it possible to replace ´DerivedA´with the input parameter, instead of hardcoding it? Jan 11, 2016 at 10:15
  • @ChristianHolmJørgensen yes it is, please see my edit above
    – 3dd
    Jan 11, 2016 at 11:01
2

If you pass in an instance of DerivedClassB, you can find all instances of DerivedClassB by comparing the actual type of the instance passed in and of the instances in the list:

public IEnumerable<BaseClass> FindClass (BaseClass @class){ 
    return myList.Where(c => c.GetType() == @class.GetType());
}
1
  • You should change your 'class' parameter something like @class. Jan 11, 2016 at 8:02
1

You can do this with the is operator. It tells you if an object is of a given type. Add a little LINQ and you get:

var firstB = myList
        .Where(c => c is DerivedClassB)
        .First();
2
  • Indeed. My bad. I didn't compile this. I'll fix it up.
    – Will
    Jan 14, 2016 at 8:44
  • Just use myList.First(c => c is DerivedClassB) if you do this. Jan 14, 2016 at 9:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.