Linq传递多个列表在哪里条件

时间:2016-12-16 04:49:46

标签: c# entity-framework linq lambda where-clause

我通过传递过滤器从db获得结果。目前我已通过code列表,我收到了正确的数据。以下是代码。

public DataTable getData(IList<string> Code, 
                         IList<string> category, 
                         IList<string> state, 
                         IList<string> Type, 
                         IList<string> general)
{
    DataTable dt = new DataTable();
    var result = _db.Sample.Where(x => Code.Contains(x.Code));

    if (result == null)
    {
        return null;
    }
    else
    {
        dt = Utility.ToDataTable(result.ToList());
    }

    return dt;
}

我必须传递4个过滤器,即category, state, type and general。此外,我必须检查它们是否都为空。

我不确定如何检查null的值,然后将其传递给查询。

任何建议都将不胜感激

2 个答案:

答案 0 :(得分:1)

您可以检查是否所有5都为空,然后执行lambda表达式。要为4个额外过滤器添加条件,请使用&&运算符并将其与代码过滤器一起添加。

public DataTable getData(IList<string> Code, IList<string> category, IList<string> state, IList<string> Type, IList<string> general)

        {
            DataTable dt = new DataTable();

              if(code==null)
              code=''
              if(category==null)
              category=''
              if(state==null)
              state=''
              if(general==null)
              general=''               

              var result = _db.Sample.Where(x => (Code.Contains(x.Code) || Code=='') && (category.Contains(x.category)|| category=='') && (state.Contains(x.state)||state=='') && (general.Contains(x.general)||general==''))


            if (result == null)
            {
                return null;
            }
            else
            {
                dt = Utility.ToDataTable(result.ToList());
            }
            return dt;
        }

答案 1 :(得分:1)

我不确定您是要检查包含所有列表还是只检查其中任何一个列表。我',为两者提供解决方案

 public DataTable getData(IList<string> Code, IList<string> category, IList<string> state, IList<string> Type, IList<string> general)

    {
        DataTable dt = new DataTable();
        var result = null;
        //result = _db.Sample.Where(x => Code.Contains(x.Code) && category.Contains(x.category) && state.Contains(x.state) && general.Contains(x.general));
        //if you wish to check for any one
        result = _db.Sample.Where(x => (Code != null && Code.Contains(x.Code)) || (category != null && category.Contains(x.category)) || (state != null && state.Contains(x.state)) || (general != null && general.Contains(x.general)));


        if (result == null)
        {
            return null;
        }
        else
        {
            dt = Utility.ToDataTable(result.ToList());
        }
        return dt;
    }