Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

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);


Friday, November 27, 2015

RavenDB Linq - How to use dynamic where clause

I faced scenario to add some specified where clause based some conditions, so that i have used following code. We can add any number of where conditions like below and execute query to RavenDB. 


public IEnumerable<Student> SearchStudents()
{
List<Expression<Func<Student, bool>>> whereConditionList = new List<Expression<Func<Student, bool>>>();

whereConditionList.Add(p => p.Name == "Balajiprasad");
whereConditionList.Add(p => p.Age > 16);
whereConditionList.Add(p => p.City == "Coimbatore");

var ravenQuery = ravenSession.Query<Student>();

foreach (var condition in whereConditionList)
  ravenQuery = ravenQuery.Where(condition);

return ravenQuery.ToList();
}