1

The goal is to build a search form that can be entered on multiple field searches. But entering all fields are optional. What is the equivalent code in LINQ? Thanks.

string str = "";
if(a!="")
    str += "f1 == a";
if(b!="")
    str += " && f2 == b";
if(c!="")
    str += " && f3 == c";

select f1, f2, f3 from p
where str;

2 Answers2

4

You can build up the query sequentially in the same way, something like this:

var query = someData.Items;

if  (a != string.Empty)
    query = query.Where(x => x.f1 == a);

if (b != string.Empty)
    query = query.Where(x => x.f2 == b);

…and so on. In the end, you have built a query with only the relevant predicates.

Jay
  • 56,361
  • 10
  • 99
  • 123
  • +1 for actually using LINQ features, and giving an answer that will perform much better than the alternative of having the SQL server/LINQ driver try to optimize out the irrelevant portions (which it usually? does, but not always) – Robert McKee Jun 03 '13 at 07:41
1

Try

from x in p where (x.f1 == a || a == "") && (x.f2 == b || b == "") && (x.f3 == c || c == "") select new { f1 = x.f1, f2 = x.f2, f3 = x.f3 }

The or on each search variable makes it ignored when empty string. I'm assuming you already took care of nulls in a, b, c.

Kirk B.
  • 456
  • 2
  • 6