ASP.NET 动态 Linq 搜索
var query = (from u in results select u).AsQueryable(); //Build where clause if (!string.IsNullOrEmpty(userRequest.searchData)) { if (userRequest.searchBy == "LastName") { var likestr = userRequest.searchData.Trim(); query = (from n in query where n.StartsWith(likestr) select n).AsQueryable(); } if (userRequest.searchBy == "FirstName") { } if (userRequest.searchBy == "Email") { //var likestr = string.Format("%{0}%", userRequest.searchData.Trim()); } if (userRequest.searchBy == "UserId") { query = query.Where(x => SqlMethods.Equals(x.UserId, Convert.ToInt32(userRequest.searchData))); } }
首先,我查询数据库并存储在 var query 中。
然后,如果有搜索数据,我会尝试使用 1 或 4 个可能的搜索来添加Where 子句。
帮助?
var query = (from u in results select u).AsQueryable(); //Build where clause if (!string.IsNullOrEmpty(userRequest.searchData)) { if (userRequest.searchBy == "LastName") { var likestr = userRequest.searchData.Trim(); query = (from n in query where n.StartsWith(likestr) select n).AsQueryable(); } if (userRequest.searchBy == "FirstName") { } if (userRequest.searchBy == "Email") { //var likestr = string.Format("%{0}%", userRequest.searchData.Trim()); } if (userRequest.searchBy == "UserId") { query = query.Where(x => SqlMethods.Equals(x.UserId, Convert.ToInt32(userRequest.searchData))); } }
First I query the DB and store in var query.
Then if there is search data I am trying to tack on the Where clause using 1 or 4 possible searches.
Help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会使用 .Contains 代替。
I would use .Contains instead.
不要尝试使用 Linq 模仿 SQL 行为。你得到了一个列表,并且可以根据对象方法查询这个列表。
试试这个:
输出:
Don't try to imitate SQL-Behaviour with Linq. You got a list and can query this list based on object methods.
Try this instead:
Output:
只需根据需要添加到查询中即可。您可以将多个“where”子句链接到其上,它们将依次执行。
ETC
Just add to the query as you need to. You can chain multiple 'where' clauses onto it and they will execute in turn.
etc
为什么不尝试一下表达式树
Why not give a shot with Expression Trees