LINQ的可选参数 [英] Linq optional parameters

查看:130
本文介绍了LINQ的可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个LINQ查询。我有一大堆的从一种形式我收集的参数,我需要过滤器的基础领域,用户正在搜索的。

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<Users> user = from user in edmxObject.Users
where user.FirstName.Contains(model.FirstName ?? user.FirstName)
&& user.UserName.Contains(model.UserName ?? user.UserName)

我有一些更多的非字符串字段筛选我需要过滤,包括长和布尔。它们可能是空,如果用户没有选择任何东西。我如何将它们包括在查询中。

I have a few more non string field filters I need to filter including long and boolean. They could be nulls if the user does not select anything. How do I include them in the query.

推荐答案

这就是为什么LINQ是如此强大,一个最好的例子 - 延迟执行。你可以建立在不同阶段的查询,并且只有当最后执行或解决将SQL语句来产生查询:

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

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

这篇关于LINQ的可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆