如何使WHERE子句中的项可选?

时间:2013-11-29 15:36:31

标签: c# linq entity-framework

public List<..> GetSomething(int column1Value, int column2Value, string column3Value)
{

 from t1 in this.DataContext.Table1
 where  t1.column1 == column1Value &&
    t1.column2 == column2Value &&
    t1.column3 == column3Value

}

现在我想重新使用上面的查询,即不想复制它,但唯一的区别是我希望t1.column3 == column3Value是选项,所以我称之为:

GetSomething(1,2,"HELLO");

GetSomething(1,2);

是否有可能使where子句的这部分成为条件?意思是如果你传入“”,那么它会忽略那个句子?

4 个答案:

答案 0 :(得分:7)

是的,请将您的陈述分为两部分:

var query = this.DataContext.Table1
                .Where( x => column1 == column1Value && x.column2 == column2Value);

if ( column3Value != "" )
    query = query.Where( x => x.column3 == column3Value);


// Your existing processing of query

答案 1 :(得分:2)

试试这个:

public List<..> GetSomething(int column1Value, int column2Value, string column3Value = null) {
  from t1 in this.DataContext.Table1
  where  t1.column1 == column1Value &&
         t1.column2 == column2Value &&
         (column3Value == null ? true :  t1.column3 == column3Value)
}

答案 2 :(得分:0)

我建议你定义OR operator以定义诸如可选的

答案 3 :(得分:0)

使参数可选,并测试缺少参数:

public List<..> GetSomething(int column1Value, int column2Value, 
                                  string column3Value = null)
{

 from t1 in this.DataContext.Table1
 where  t1.column1 == column1Value &&
    t1.column2 == column2Value &&
    (column3Value == null || t1.column3 == column3Value)

}