使用linq函数实现动态查询

时间:2016-09-02 10:48:08

标签: c# linq

我正在尝试实现一个代码块,它可以动态地将一个where子句添加到linq查询中。它完全有助于我只考虑全文框 在我的搜索过程中跳过空控件。现在问题是,尽管我已经添加到我的Linq查询中的所有条件,它返回所有行并忽略where子句。

是什么原因以及如何避免这个问题?

这里我有一个简单的抽象BaseEntity类,它只包含一个名为Id的字段:

public abstract class BaseEntity
    {
        public virtual int Id { get; set; }
    }

我的EmailEntity类继承自此BaseEntity:

    public class EmailEntity : BaseEntity
    {
        public string Address { get; set; }
        public string Pwd { get; set; }
        public string Hint { get; set; }
        public EmailGroup? EmailGroup { get; set; }
    }

这是我创建查询的地方:

 private void BtnSearch_Click(object sender, RoutedEventArgs e)
        {
            var mails = new List<EmailEntity>();    
            using (var op = new OperationContext())
            {
                var query = op.EmailEntities;
                if (!string.IsNullOrEmpty(SearchEmailTxt.Text))
                    query.Where(item => item.Address == SearchEmailTxt.Text);
                if (!string.IsNullOrEmpty(SearchEmailIdTxt.Text))
                    query.Where(item => item.Id == Convert.ToInt16(SearchEmailIdTxt.Text));
                if (SearchEmailGroupCombo.SelectedItem != null)
                    query.Where(item => item.EmailGroup.ToString() == SearchEmailGroupCombo.SelectedItem.ToString());
                var result=query.ToList();
                result.ForEach(mails.Add);
                EmailDataGrid.ItemsSource = mails;
            }
        }

1 个答案:

答案 0 :(得分:4)

因为query.Where返回了查询而你忽略了结果,这会让你开始。您应该更改代码,例如query = query.Where(....);

private void BtnSearch_Click(object sender, RoutedEventArgs e)
{
    var mails = new List<EmailEntity>();    
    using (var op = new OperationContext())
    {
        IQueryable<EmailEntity> query = op.EmailEntities;
        if (!string.IsNullOrEmpty(SearchEmailTxt.Text))
            query = query.Where(item => item.Address == SearchEmailTxt.Text);
        if (!string.IsNullOrEmpty(SearchEmailIdTxt.Text))
            query = query.Where(item => item.Id == Convert.ToInt16(SearchEmailIdTxt.Text));
        if (SearchEmailGroupCombo.SelectedItem != null)
            query = query.Where(item => item.EmailGroup.ToString() == SearchEmailGroupCombo.SelectedItem.ToString());
        var result=query.ToList();
        result.ForEach(mails.Add);
        EmailDataGrid.ItemsSource = mails;
    }
}