linq动态查询

近日做几个项目用到linq动态查询,但微软官方所提供的那些动态查询机制相当复杂,   网上也有不少网友发过一些动态查询的方案,本人觉得那些方案比较繁索,也不易理解,今提供一种易理解简单实用的方法.

方法如下:

在中间层写:

  public List<View_InvoiceTransferLog> GetTransferLogByCondition(DateTime? startDate,
            DateTime? endDate,int? startNum,int? endNum, InvoiceLogType logType)
        {
            int theType = (int)logType;
            IQueryable<View_InvoiceTransferLog> query = from view in Context.View_InvoiceTransferLogs
                                                        where
                                                        (startDate == null || view.LogDate >= startDate) &&
                                                        (endDate == null || view.LogDate <= endDate) &&
                                                        (startNum == null || view.InvoiceStartNum >= startNum) &&
                                                        (endNum == null || view.InvoiceEndNum <= endNum) &&
                                                        view.TransferType == theType
                                                        select view;
            return query.ToList();
        }

调用过程如下:

 在ui层写

        protected void SearchButton_Click(object sender, EventArgs e)
        {
            if (!HaveCondition())
            {
                GetAllDataByStatus();
                return;
            }
            DateTime? startDate = null;
            DateTime? endDate = null;
            int? startNumber = null;
            int? endNumber = null;

            if (!ValidateData())
            {
                return;
            }
           
            //get select condition
            //
            if (!string.IsNullOrEmpty(StartDate.Text.Trim()))
            {
                startDate = DateTime.Parse(StartDate.Text.Trim());
            }
            if (!string.IsNullOrEmpty(EndDate.Text.Trim()))
            {
                endDate = DateTime.Parse(EndDate.Text.Trim());
            }
            if (!string.IsNullOrEmpty(StartNum.Text.Trim()))
            {
                startNumber = int.Parse(StartNum.Text.Trim());
            }
            if (!string.IsNullOrEmpty(EndNum.Text.Trim()))
            {
                endNumber = int.Parse(EndNum.Text.Trim());
            }
            List<View_InvoiceTransferLog> list = _control.GetTransferLogByCondition(startDate, endDate, startNumber, endNumber,InvoiceLogTypeEnum);
            gd.DataSource = list;
            gd.DataBind();
        }

简单实用的一种动态查询方法,就这么几句即可实现.本文属本人原创,转载请注明出处.代码开源.

你可能感兴趣的:(LINQ)