Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34180

Adding function to my class

I have a class, and there is a List in this class, I want to add a Where function to my class that calls the Where function of the List, Something like this:

 public class MyClass<T> where T : class
 {    
    public Func<T, IEnumerable<T>>  Where{ get; set; }
    public List<T> mylist = new List<T>();
    public MyClass()
    {
         Where = mylist.Where;
    }
 }

I'm getting the Error:

No overload for 'Where' matches delegate 'Func<T, IEnumerable<T>>

Upvotes: 1

Views: 50

Answers (3)

ventiseis
ventiseis

Reputation: 3099

List<T> provides no Where-Function. Where is an extension function for enumerables, see MSDN. See the other answers how you can correct your property to match the type of the extension function.

Of course I have no idea what you want to achive, but if you want a list class with an assignable filter, you can use something like this:

public class MyClass<T> : IEnumerable<T> where T : class {

    public Func<T, bool> Filter { get; set; }
         = T => true; // default: no filter

    public List<T> mylist = new List<T>();

    public IEnumerator<T> GetEnumerator()
        => mylist.Where(Filter).GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator()
        => mylist.Where(Filter).GetEnumerator();
}

Upvotes: 0

erisco
erisco

Reputation: 14329

As per IEnumerable on MSDN there is IEnumerable<TSource> Where<TSource>(Func<TSource, Boolean>) and IEnumerable<TSource> Where<TSource>(Func<TSource, Int32, Boolean>).

These are castable to Func<Func<TSource, Boolean>, IEnumerable<TSource>> and Func<Func<TSource, Int32, Boolean>, IEnumerable<TSource>> respectably.

Neither match the type declared for your property "Where", which is Func<T, IEnumerable<T>>, and that is why the compiler tells you No overload for 'Where' matches delegate 'Func<T, IEnumerable<T>>.

You need to choose an appropriate delegate type.

Upvotes: 2

Lee
Lee

Reputation: 144206

Your delegate has the wrong type, it should be:

public Func<Func<T, bool>, IEnumerable<T>> Where { get; set; }

Upvotes: 2

Related Questions