2010-12-09 70 views
0
 

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查詢中。ASP.NET動態Linq搜索

然後,如果有搜索數據,我嘗試使用1或4個可能的搜索來檢查Where子句。

幫助?

回答

0

我會使用.Contains來代替。

+0

他只是想先從uservalue的名字了一槍。 – Christian 2010-12-09 15:27:39

0

不要試圖模仿Linq的SQL行爲。你有一個列表,並可以基於對象方法查詢這個列表。

試試這個:

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", "[email protected]"); 
      table.Rows.Add(2, "Christoph", "Bar", "[email protected]"); 
      table.Rows.Add(3, "Michael", "FooBar", "[email protected]"); 
      table.Rows.Add(4, "Andreas", "BarFoo", "[email protected]"); 
      table.Rows.Add(5, "Carl", "Bar", "[email protected]"); 

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

輸出:

//Query ID 
1 
//Query Firstname 
1 
2 
5 
+0

我編輯了我的問題,所以看看。 – Mark 2010-12-09 15:42:41

0

,你只是需要添加到查詢。您可以將多個'where'子句鏈接到它上面,並且它們將依次執行。

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