tags:

views:

13634

answers:

5

Can you explain me;

  • What is Predicate Delegate ?
  • Where should we use predicates ?
  • Any best practices about predicates ?

Descriptive source code will be appreciated,

Thanks for all replies !

A: 

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):
Adam Carr
+53  A: 

A predicate is a function that returns true or false. A predicate delegate is a reference to a predicate.

So basically a predicate delegate is a reference to a function that returns true or false. Predicates are very useful for filtering a list of values - here is an example.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
     List<int> list = new List<int> { 1, 2, 3 };

     Predicate<int> predicate = new Predicate<int>(greaterThanTwo);

     List<int> newList = list.FindAll(predicate);
    }

    static bool greaterThanTwo(int arg)
    {
     return arg > 2;
    }
}

Now if you are using C# 3 you can use a lambda to represent the predicate in a cleaner fashion:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
     List<int> list = new List<int> { 1, 2, 3 };

     List<int> newList = list.FindAll(i => i > 2);
    }
}
Andrew Hare
+2  A: 

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.

LukeH
+20  A: 

Leading on from Andrew's answer with regards to c#2 and c#3 ... you can also do them inline for a one off search function (see below).

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> list = new List<int> { 1, 2, 3 };

        List<int> newList = list.FindAll(delegate(int arg)
                           {
                               return arg> 2;
                           });
    }
}

Hope this helps.

WestDiscGolf
That's actually pretty handy. Nice.
Repo Man
Exactly what I was looking for.
rodey
A: 

If you're in VB 9 (VS2008), a predicate can be a complex function:

Dim list As New List(Of Integer)(New Integer() {1, 2, 3})
Dim newList = list.FindAll(AddressOf GreaterThanTwo)
...
Function GreaterThanTwo(ByVal item As Integer) As Boolean
    'do some work'
    Return item > 2
End Function

Or you can write your predicate as a lambda, as long as it's only one expression:

Dim list As New List(Of Integer)(New Integer() {1, 2, 3})
Dim newList = list.FindAll(Function(item) item > 2)
danlash