0

I have a number of controls that inherit from a generic base class and this class implements an interface IMyInterface.

So far I tried:

var results = from c in this.Controls.Cast<Control>()
              where c.GetType().GetInterfaces().Contains(typeof(IMyInterface))
              select c as IMyInterface;

However, the above doesn't return any results even though it should.

How can I use Linq to get a list of controls on a form that implement this interface?

0

3 Answers 3

2

If I understood you correctly, you could basically use:

var results = this.Controls.OfType<BaseGeneric>().ToList();

Sign up to request clarification or add additional context in comments.

1 Comment

OfType<IMyInterface>.
1

Given the following extension method:

public static class TypeExtensions
{
    public static IEnumerable<Type> BaseTypesAndSelf(this Type type)
    {
        while (type != null)
        {
            yield return type;
            type = type.BaseType;
        }
    }
}

You want something like:

        var result = from c in this.Controls.Cast<Control>()
                     where c.GetType().BaseTypesAndSelf().Any(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(BaseGeneric<>))
                     select c;

You might want to have your BaseGeneric<T> inherit from some even more abstract BaseGenericBase, or implement some non-generic IBaseGeneric interface, to make this sort of thing simpler.

Comments

0
class Program
{
    static void Main(string[] args)
    {

        A test1 = new A();
        B test2 = new B();
        C test3 = new C();

        List<object> test4 = new List<object>() { test1, test2, test3 };
        List<object> test5 = test4.FindAll(x => x is A).ToList();

    }
}

public class A
{

    public A() { }

}

public class B
{

    public B() {}


}

public class C : A
{

    public C()
        :base()
    {

    }

}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.