c# – Predicate<T> and Func<string> as T

Question:

There is a List <Func <string >> you need to call List.RemoveAll (). You need to pass a Predicate <T> there. only certain functions need to be removed. On MSDN I saw an example with Point, but an attempt to redo it in the same way under Func does not work. What is the problem?

    List<Func<string>> _list;
    public MainWindow()
    {
        _list = new List<Func<string>>();
        _list.Add(this.test);
        _list.Add(this.test2);
        _list.Add(this.test);
        _list.Add(this.test2);
        _list.Add(this.test);

        Predicate<Func<string>> pre = ValidateFunc(test2,nameof(test2));// тут функция и подчеркивается с ошибкой
    }

    private static bool ValidateFunc(Func<string> obj,string targetName)
    {
        return targetName == nameof(obj);
    }

    string test()
    {
        textBox.Text += " 2";
        return "";
    }
    string test2()
    {
        textBox.Text += " 3";
        return "";
    }

Error: Unable to implicitly convert type "bool" to "System.Predicate <System.Func <string >>"

If, as on MSDN without parameters, then the error is: There is no overloaded method for "ValidateFunc", which corresponds to the delegate "Predicate <Func <string >>"

Answer:

I suggest this option:

Predicate<Func<string>> pre = item => item == this.test;

In particular, when using this predicate as an argument to the _list.RemoveAll method, all occurrences of the test method will be removed from the _list collection.

Or, if instead of referring to a method, you want to use a string with the method name:

Predicate<Func<string>> pre = item => item.Method.Name == "test";

And I could not understand the purpose of your ValidateFunc method. In it, you compare the targetName string with nameof(obj) (that is, with the string constant "obj" ).

Scroll to Top