字符串到LINQ表达式? [英] String to LINQ expression?
本文介绍了字符串到LINQ表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将带有查询的字符串转换为实际的LINQ表达式,以便执行它?
How can I transform the string with the query in it into an actual LINQ expression so I can execute it?
if(email!= null)
{
query += "x => x.Email.Contains(email)";
}
if (firstname != null)
{
query += "&& x.FirstName.Contains(firstname)";
}
if (lastname != null)
{
query += "&& x.LastName.Contains(lastname)";
}
return context.UserAccounts.Where(query).ToList();
推荐答案
尝试一下:
<your collection>.
.Where(o => (email!= null)? o.Email.Contains(email) : true).
.Where(o => (firstname != null)? o.FirstName.Contains(firstname) : true).
.Where(o => (lastname != null)? o.LastName.Contains(lastname) : true).
ToList();
基本上,这意味着过滤器仅在满足条件时才适用(就像if语句中一样).
Basically it means the filter will apply only when the condition is met (just like in your if sentences).
这篇关于字符串到LINQ表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文