Predicate Delegates in C#

后端 未结 10 1156
一个人的身影
一个人的身影 2020-11-27 09:13

Can you explain to me:

  • What is a Predicate Delegate?
  • Where should we use predicates?
  • Any best practices when using predicates?

相关标签:
10条回答
  • 2020-11-27 09:26

    Simply -> they provide True/False values based on condition mostly used for querying. mostly used with delegates

    consider example of list

    List<Program> blabla= new List<Program>();
            blabla.Add(new Program("shubham", 1));
            blabla.Add(new Program("google", 3));
            blabla.Add(new Program("world",5));
            blabla.Add(new Program("hello", 5));
            blabla.Add(new Program("bye", 2));
    

    contains names and ages. Now say we want to find names on condition So I Will use,

        Predicate<Program> test = delegate (Program p) { return p.age > 3; };
            List<Program> matches = blabla.FindAll(test);
            Action<Program> print = Console.WriteLine;
            matches.ForEach(print);
    

    tried to Keep it Simple!

    0 讨论(0)
  • 2020-11-27 09:27

    The predicate-based searching methods allow a method delegate or lambda expression to decide whether a given element is a “match.” A predicate is simply a delegate accepting an object and returning true or false: public delegate bool Predicate (T object);

       static void Main()
            {
                string[] names = { "Lukasz", "Darek", "Milosz" };
                string match1 = Array.Find(names, delegate(string name) { return name.Contains("L"); });
                //or
                string match2 = Array.Find(names, delegate(string name) { return name.Contains("L"); });
                //or
                string match3 = Array.Find(names, x => x.Contains("L"));
    
    
                Console.WriteLine(match1 + " " + match2 + " " + match3);     // Lukasz Lukasz Lukasz
            }
            static bool ContainsL(string name) { return name.Contains("L"); }
    
    0 讨论(0)
  • 2020-11-27 09:31

    What is Predicate Delegate?

    1) Predicate is a feature that returns true or false.This concept has come in .net 2.0 framework. 2) It is being used with lambda expression (=>). It takes generic type as an argument. 3) It allows a predicate function to be defined and passed as a parameter to another function. 4) It is a special case of a Func, in that it takes only a single parameter and always returns a bool.

    In C# namespace:

    namespace System
    {   
        public delegate bool Predicate<in T>(T obj);
    }
    

    It is defined in the System namespace.

    Where should we use Predicate Delegate?

    We should use Predicate Delegate in the following cases:

    1) For searching items in a generic collection. e.g.

    var employeeDetails = employees.Where(o=>o.employeeId == 1237).FirstOrDefault();
    

    2) Basic example that shortens the code and returns true or false:

    Predicate<int> isValueOne = x => x == 1;
    

    now, Call above predicate:

    Console.WriteLine(isValueOne.Invoke(1)); // -- returns true.
    

    3) An anonymous method can also be assigned to a Predicate delegate type as below:

    Predicate<string> isUpper = delegate(string s) { return s.Equals(s.ToUpper());};
        bool result = isUpper("Hello Chap!!");
    

    Any best practices about predicates?

    Use Func, Lambda Expressions and Delegates instead of Predicates.

    0 讨论(0)
  • 2020-11-27 09:31

    A delegate defines a reference type that can be used to encapsulate a method with a specific signature. C# delegate Life cycle: The life cycle of C# delegate is

    • Declaration
    • Instantiation
    • INVACATION

    learn more form http://asp-net-by-parijat.blogspot.in/2015/08/what-is-delegates-in-c-how-to-declare.html

    0 讨论(0)
  • 2020-11-27 09:35

    Just a delegate that returns a boolean. It is used a lot in filtering lists but can be used wherever you'd like.

    List<DateRangeClass>  myList = new List<DateRangeClass<GetSomeDateRangeArrayToPopulate);
    myList.FindAll(x => (x.StartTime <= minDateToReturn && x.EndTime >= maxDateToReturn):
    
    0 讨论(0)
  • 2020-11-27 09:41

    There's a good article on predicates here, although it's from the .NET2 era, so there's no mention of lambda expressions in there.

    0 讨论(0)
提交回复
热议问题