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 !
Can you explain me;
Descriptive source code will be appreciated,
Thanks for all replies !
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):
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);
}
}
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.
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)