Thursday, March 20, 2014

Combining Predicates in c#

Today, I was looking for a way to combine 2 or more predicates, We have found an MSDN post about it HERE. It explains 3 different ways to combine predicates using LINQ expressions. .

But, Can we make it simple and cool?
I guess it's time to use our creativity skills.
Think about it we just need to merge lambda expressions. In order to merge lambda expressions we always use &&/!!, so Can we do the same here?
Here's our solution below:
static void Main(string[] args)
{
    Func<Car, bool> theCarIsRed = c => c.Color == "Red";
    Func<Car, bool> theCarIsCheap = c => c.Price < 10.0;
    Func<Car, bool> theCarIsLuxury = c => c.Model == "Audi";
    Func<Car, bool> theCarIsRedOrCheap =    c =>     theCarIsRed(c)
                                                                             && theCarIsCheap(c)
                                                                             || theCarIsLuxury(c);
    List<Car> cars = new List<Car>();
    cars.Add(new Car { Color = "Red", Price = 7 });
    cars.Add(new Car { Color = "Yellow", Price = 90, Model= "Audi" });
    cars.Add(new Car { Color = "Red", Price = 11, Model = "Toyota" });
    cars.Add(new Car { Color = "Red", Price = 60, Model = "Audi" });
    Console.WriteLine("available options: " + cars.Where(theCarIsRedOrCheap).Count());
    Console.ReadLine();
}
class Car
{
    public string Color { get; set; }
    public long Price { get; set; }
    public string Model { get; set; }
}

Conclusion
Combining predicates means combining lambda expressions.  

No comments:

Post a Comment