使用Linq删除和添加搜索过滤器

时间:2012-10-25 20:48:09

标签: c# asp.net linq

我有一个搜索字段,它使用下拉列表按部门筛选搜索结果。

我终于让它工作得很好但现在我想做一个全部选项来否定这一点。下拉值等于int。我仍然在学习,所以我能绕过这个问题的唯一方法是在where查询中使用if else语句。当我这样做时,我看到了很多红色。

下拉列表中有5个选项。值为1到5. 5 =全部。我想基本上停止按部门搜索或删除t0.DivisionID == DDLInt &&

string DDL = DDLAddDivision.SelectedValue;
int DDLInt;
if (int.TryParse(DDL, out DDLInt))
{
    int searchID;
    if (!int.TryParse(txtSearch.Text.Trim(), out searchID))
        searchID = -1;  // set to an invalid ID


    ItemContext db = new ItemContext();
    var q = (from t0 in db.Item
             join t1 in db.Categories on t0.CategoryID equals t1.CategoryID
             join t2 in db.Divisions on t0.DivisionID equals t2.DivisionID

             where


              t0.DivisionID == DDLInt &&

                 //Contains

            (
             t0.ItemName.Contains(txtSearch.Text.Trim()) ||
             t0.Email.Contains(txtSearch.Text.Trim()) ||
             t0.Description.Contains(txtSearch.Text.Trim()) ||
             t0.Phone.Contains(txtSearch.Text.Trim()) ||
             t0.ItemID.Equals(searchID)
             )
             group t0 by new
             {
                 t0.ItemID,
                 t0.ItemName,
                 t0.Description,
                 t0.Phone,
                 t0.Email,
                 t0.DivisionID,
                 t0.CategoryID,
                 t1.CategoryName,
                 t2.DivisionName


             } into i

             select new
             {
                 i.Key.ItemID,
                 i.Key.ItemName,
                 i.Key.Description,
                 i.Key.Email,
                 i.Key.Phone,
                 i.Key.CategoryName,
                 i.Key.DivisionName,
                 i.Key.CategoryID,
                 i.Key.DivisionID

             });

    if (q.Any() == false)
    {
        ResultsLabelId.Visible = true;
    }
    else
    {
        ResultsLabelId.Visible = false;
    }

    //bind and return
    lv.DataSource = q.ToList();
    lv.DataBind();

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

如何用以下代码替换该行:

(DDLInt == 5 || t0.DivisionID == DDLInt) &&