簡單多條件動態查詢的實現

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   os   

今天公司有個項目需要到多個條件查詢的功能,以前兩三個條件的時候就用if去判斷,草草了事,由於這次有5-9個條件不等的情況下,總不能都用if吧,雖說能實現,不過這代碼看上去也太難看,最重要的是沒有重用性,也不方便修改,網上找了下,五花八門的,要費時間去理解它,還不如自己封裝下,也便於以後的使用:

我前端用的是BUI來設計的,所以條件的傳遞方式是get/post,所以這個方法是針對“查詢條件來自get/post方式的”,如果是用伺服器控制項傳的,這種方式是不適合的哦

好了,首先,為了方便儲存每個欄位的索引值和比較關係,先建立一個Condition類,方便以後操作,代碼如下:

 

 public class Condition    {        //欄位名        public string paramName { get; set; }        //欄位值        public string paramValue { get; set; }        //操作符        public ConditionOperate Operation { get; set; }        // 查詢所用到的運算操作符        public enum ConditionOperate : byte        {            Equal,           // 等於            NotEqual,      // 不等於            Like,             // 模糊查詢            Lessthan,      // 小於等於            GreaterThan,  // 大於等於            Less,          //小於            Greater      //大於        }    }

 

接著,建立一個拼接查詢條件的類:

 

  public static class ConditionBuilder    {        public static string  getWhere<T>(List<Condition> conditions)        {            //擷取類型            Type t = typeof(T);            //擷取類型中的屬性集合            PropertyInfo[] properties = t.GetProperties();            foreach (PropertyInfo p in properties)            {                string colName = p.Name;                //這裡參數是通過url地址欄來(get方式)的,所以用Request.QueryString,如果是post(方式),改做下面的Request.From就好                for (int i = 0; i < HttpContext.Current.Request.QueryString.Count; i++)                {                    string value = HttpContext.Current.Request.QueryString[i].ToString();                    //如果欄位存在並且不為空白                    if (colName == HttpContext.Current.Request.QueryString.GetKey(i).ToString() && !string.IsNullOrEmpty(value))                    {                        Condition ct = new Condition();                        ct.paramName = colName;                        ct.paramValue = value;                        ct.Operation = Condition.ConditionOperate.Equal;                        conditions.Add(ct);                    }                }            }            // 數組元素的順序應該與ConditionOperate枚舉值順序相同            string[] operateType = { " = ", " <> ", " Like ", " <= ", " >= ", " < ", " > " };            StringBuilder strWhere = new StringBuilder();            strWhere.Append(" 1=1 ");            foreach (Condition item in conditions)            {                int index = (int)item.Operation;                strWhere.Append(" and " + item.paramName + operateType[index] + "‘" + item.paramValue + "‘");            }              return strWhere.ToString();        }    }

 

這裡,後台直接調用

        List<Condition> conditions = new List<Condition>();        string strWhere = ConditionBuilder.getWhere<Sends>(conditions);

當然,有一些特殊欄位需要做特殊處理的話,也可以在調用getWhere先處理下。
最後的結果是:

訪問http://localhost:14073/Index/GetData?a=a1&b=b1&start=0&limit=10&pageIndex=0&field=SendsID&direction=ASC&Receiver=%E9%83%AD%E4%BC%9F&FromUserName=8&FromSchoolName=87&SmsContent=8&SmsType=1&SendStatus=1&StartTime=&EndTime=&_=1404199763638

得到:1=1 and FromUserName = ‘8‘ and FromSchoolName = ‘87‘ and SmsType = ‘1‘ and SmsContent = ‘8‘ and SendStatus = ‘1‘ and Receiver = ‘郭偉‘

 

 

本人也是菜鳥,此方法只能用來處理普通的查詢,對於複雜條件查詢的還希望有高手賜教,如果大家有其他好的,也希望能分享下。當然,此方法也不適用於linq和ef,

如果有做過linq和ef動態條件查詢的朋友也希望分享下。謝謝!

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.