Linq optional parameters

后端 未结 2 1451
日久生厌
日久生厌 2021-01-05 07:34

I have a linq query. I have a bunch of parameters from a form I collect where I need to filter based of fields the user is searching for.

IQueyable

        
2条回答
  •  感情败类
    2021-01-05 08:23

    This is one of the best examples of why LINQ is so powerful - deferred execution. You can build up the query in different phases, and only when the query is finally executed or resolved will the SQL statement be generated:

    var query = edmxObject.Users.AsQueryable();
    
    if (! String.IsNullOrEmpty(model.FirstName)) {
        query = from user in query
                where user.FirstName.Contains(model.FirstName)
                select user;
    }
    if (! String.IsNullOrEmpty(model.UserName) {
        query = from user in query
                where user.UserName.Contains(model.UserName)
                select user;
    }
    
    // this will cause the query to execute get the materialized results
    var result = query.ToList();
    

提交回复
热议问题