ASP.NET Dynamic Linq Search
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?
I would use .Contains instead.
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:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("FIRSTNAME", typeof(string));
table.Columns.Add("LASTNAME", typeof(string));
table.Columns.Add("EMAIL", typeof(string));
// Here we add five DataRows.
table.Rows.Add(1, "Chris", "Foo", "chris.foo@mail.com");
table.Rows.Add(2, "Christoph", "Bar", "christoph.bar@mail.com");
table.Rows.Add(3, "Michael", "FooBar", "michael.foobar@mail.com");
table.Rows.Add(4, "Andreas", "BarFoo", "andreas.barfoo@mail.com");
table.Rows.Add(5, "Carl", "Bar", "carl.bar@mail.com");
Console.WriteLine("//Query ID");
var query1 = (from dr in table.AsEnumerable() where dr.Field<int>("ID") == 1 select dr).FirstOrDefault();
Console.WriteLine(query1.Field<int>("ID"));
Console.WriteLine("//Query Firstname");
var query2 = (from dr in table.AsEnumerable() where dr.Field<string>("FIRSTNAME").StartsWith("C") select dr).ToList<System.Data.DataRow>();
foreach (var q in query2)
{
Console.WriteLine(q.Field<int>("ID"));
}
Console.ReadLine();
}
}
}
Output:
//Query ID
1
//Query Firstname
1
2
5
Just add to the query as you need to. You can chain multiple 'where' clauses onto it and they will execute in turn.
var query = (from u in results select u);
if (!string.IsNullOrEmpty(userRequest.searchData))
{
if (userRequest.searchBy == "LastName")
{
var likestr = userRequest.searchData.Trim();
query = (from n in query where n.LastName.StartsWith(likestr) select n);
}
if (userRequest.searchBy == "UserId")
{
var userId = Convert.ToInt32(userRequest.searchData);
query = (from n in query where n.UserId == userId select n);
}
etc
Why not give a shot with Expression Trees
精彩评论