Thursday, October 27, 2016

C# - Passing Linq condition as parameter

We can pass LINQ conditions dynamically as parameter, Lets consider simple example to get Single property and multiple properties by condition. We can use this for Generic Repository Pattern also.

Implementation below,

      public Student GetSingleObjectByCondition(System.Func<Student, bool> predicate)
        {
                var result = default(Student);
            using (var efContext = new DbContext())
            {
                result = efContext.Students.FirstOrDefault(predicate);
            }
            return result;
 }    

     public List<Student> GetMultipleObjectsByCondition(Func<Student, bool> predicate)
        {
            var result = default(List<Student>);
            using (var efContext = new DbContext())
            {
                result = efContext.Students.Where(predicate).ToList<Student>();
            }
            return result;
  }          

    }



How to call the method,

   Func<Student, bool> selector = str => str.Name == "Balaji";

  var student = _studentRepository.GetSingleObjectByCondition(selector);



 Func<Studentbool> selector = str => str.Rank <= 5;


  var students = _studentRepository.GetMultipleObjectsByCondition(selector);