LINQ:如何构建动态查询? [英] LINQ: How to build dynamic query?

查看:94
本文介绍了LINQ:如何构建动态查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

与逆戟鲸玩了一点,并通过构建动态

查询来解决问题。我想构建一个动态的where子句,但只有参数

不为空=(TextBox.Text!="")。

通过构建一个字符串很简单,但如何用LINQ做呢?


string sql ="" ;;

if(TextBox1.Text!=" ")

sql + =" Columns_1 =''" + TextBox1.Text +"''" ;;

if(TextBox2.Text!=" ;")

sql + =" Columns_2 =''" + TextBox2.Text +"''" ;;

如何将if查询包括在内linq ???


var query =来自db.MyTable中的c

其中c.Column_1 == TextBox1.Text&&

c.Column_2 == TextBox2.Text

选择c;


谢谢!


-Stefan

Hello,
played a little with orcas and went into a problem by building dynamic
queries. I want to build a dynamic where clause but only with parameters that
are not empty =(TextBox.Text != "").
Doing this by building a string is very simple, but how to do it with LINQ?

string sql = "";
if (TextBox1.Text != "")
sql += "Columns_1=''"+TextBox1.Text+"''";
if (TextBox2.Text != "")
sql += "Columns_2=''"+TextBox2.Text+"''";
How to include the if query to linq???

var query = from c in db.MyTable
where c.Column_1 == TextBox1.Text &&
c.Column_2 == TextBox2.Text
select c;

Thank you!

-Stefan

推荐答案

(稍微简单):


if(!string.IsNullOrEmpty(inputA)) {

query = query.Where(x = x.PropertyB == inputA);

}

i f(!string.IsNullOrEmpty(inputB)){

query = query.Where(x = x.PropertyB == inputB);

}


Marc
(slightly simpler):

if (!string.IsNullOrEmpty(inputA)) {
query = query.Where(x =x.PropertyB == inputA);
}
if (!string.IsNullOrEmpty(inputB)) {
query = query.Where(x =x.PropertyB == inputB);
}

Marc


[注意拼写错误 - 应该是PropertyA]
[watch for typo - should have been PropertyA]


它'' s实际上比忽略查询稍微容易一点
It''s actually slightly easier than that if you ignore the query

表达式语法:

...

查询在许多情况下,表达式语法很好,但只需添加一个

" where"我更喜欢使用直接方法调用。
expression syntax:
...
Query expression syntax is nice in many cases, but just to add a
"where" clause I prefer to use the direct method call.



是的 - 我在我的初始帖子后发布了这个帖子(尽管有一个

错字)...我同意。

Yes - I posted that right after my initial post (albeit with a
typo)... I agree.


如果有必要,您甚至可以编写一个方法来抽象出来。
You could even write a method to abstract it out if necessary.



注意扩展这个?我能想出几种解释这个问题的方法,但我只是对你的意思感兴趣......?


Marc

Care to expand on this? I can think of a few ways of interpreting
this, but I''m just interested in how you mean it...?

Marc


这篇关于LINQ:如何构建动态查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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