46

I am trying to make a LINQ statement where the where clause comes from a variable. For example:

string whereClause = address.zip == 23456;
var x = from something in someList where whereClause;

Is this possible? I cannot seem to get it to work.

thanks,

Update - my where clause is predefined and will be based on user input so I don't think this will work for me. Basically whereClause is not constructed in the method, it is a parameter of the method which does the LINQ. I didn't explain that well here is a better example:

public void doLnq(string whereClause)
{
   var x = from something in someList where whereClause;
   dowork(x);
}

Update - Just to sum up some of the suggestions and centralize everything.

I cannot use a switch to generate the where clause because there are way to many possibilities.

The dynamic linq post that a few of you have posted does look promising but i am having trouble related the linq to sql example to my linq to objects problem.

and @sLaks after looking through msdn http://msdn.microsoft.com/en-us/library/bb353734.aspx I am having trouble figuring out where you meant to use AsQueryable

thanks,

kds6253
  • 795
  • 1
  • 11
  • 17
  • Er, no. The where clause is just *not* a string, it's an expression that returns a boolean. Except... see SLaks's link! – sq33G Jan 03 '12 at 21:22
  • @sq33G the string in this situation would be "address.zip == 23456" I would like to use at as the expression. The string comes from user input so they can do custom searches. Does that make sense? – kds6253 Jan 03 '12 at 21:25
  • I'm guessing that the user is choosing the field (field == value) from a dropdown. So you can probably use a switch statement to build a Func to send as a Where delegate. – sq33G Jan 03 '12 at 21:29
  • Yes and No. Yes that is how the string is defined, but the value portion is custom text so only one side of the statement is controllable. – kds6253 Jan 03 '12 at 21:34
  • 1
    That's fine, you can make your Where with that: something => something./*field*/ == inputString – sq33G Jan 03 '12 at 21:40
  • the field portion must be hard coded though and with over 100 possibilities that switch statement is not practical. I should have mentioned that above. – kds6253 Jan 03 '12 at 21:43
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/6361/discussion-between-sq33g-and-kds6253) – sq33G Jan 03 '12 at 21:49

5 Answers5

73

You need to assembly an Expression<Func<T, bool>> and pass it to the Where() extension method:

Expression<Func<T, bool>> whereClause = a => a.zip == 23456;
var x = frSomeList.Where(whereClause);

EDIT: If you're using LINQ to Objects, remove the word Expression to create an ordinary delegate.

SLaks
  • 800,742
  • 167
  • 1,811
  • 1,896
  • 1
    With a `linq-to-objects` tag, would an *Expression* be appropriate? – Anthony Pegram Jan 03 '12 at 21:01
  • @kds6253: Then you can take a delegate as a parameter. If you need to use a string, you can use dynamic LINQ (but it will be slower) – SLaks Jan 03 '12 at 21:08
  • speed shouldn't be an issue, they will be relatively simple queries. Would you happen to have a short example of dynamic linq – kds6253 Jan 03 '12 at 21:11
  • 3
    http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx – SLaks Jan 03 '12 at 21:11
  • please refer to my comment on the similar answer below. thanks. – kds6253 Jan 03 '12 at 21:22
  • @kds6253: Just call `AsQueryable()` – SLaks Jan 03 '12 at 21:27
  • this solution works. Thanks to @sq33G for helping out as well. – kds6253 Jan 03 '12 at 22:16
  • @SLaks That for that. `T` is used to qualify the expression that's being created, but what does the `bool` mean exactly ? – Francis Ducharme Jul 04 '14 at 16:18
  • @FrancisDucharme: Wrong. `T` and `bool` are the type parameters of the `Func` delegate. `T` is the parameter type; `bool` is the return type. (see the delegate declaration) – SLaks Jul 04 '14 at 16:19
  • guys if whereClause take two parameters, how to use it in where clause @SLaks – asem mokllati Jul 07 '17 at 16:43
  • @asemmokllati: Your question makes no sense. `Where()` only passes one parameter (unless you mean the index, in which case just make an expression that takes two parameters). – SLaks Jul 07 '17 at 17:25
11

This:

var query = from something in someList where whereClause;

is shorthand for:

var query = someList.Where(something => whereClause);

Assuming someList is an IEnumerable<Address>, Where refers to the Enumerable.Where Extension Method. This method expects a Func<Address, bool> which you can define as follows:

Func<Address, bool> whereClause = address => address.Zip == 23456;
var query = someList.Where(whereClause);
dtb
  • 198,715
  • 31
  • 379
  • 417
  • How could it be used in non-lambda form? when I use this form: var query = from something in someList where whereClause; it says it expects a bool. Thanks – Amir Parsi Feb 11 '21 at 04:07
4

As Richard has pointed out, the Dynamic Query Library can be used to build dynamic filter expressions. When using Linq-To-Objects make sure to convert your IEnumerable<T> to a IQueryable<T> first. Here is an (incomplete) example:

using System.Linq.Dynamic;

namespace System.Linq.Dynamic
{
  public class Example
  {
   // Assuming some value is assigned to below field somewhere... 
   private IEnumerable<Address> m_Addresses;

   public void FilterByZipCode(string zipCode)
   {
      var x = m_Addresses.AsQueryable().Where("Zip == @0", zipCode);
      dowork(x);
   }
  }

  public class Address
  {  
     public String Zip { get; set; }

     // More Properties...  
  }
}
afrischke
  • 3,706
  • 15
  • 30
1

That's a built-in Feature of LINQ. Just use the Where extension method.

See LINQ Query Syntax versus Method Syntax (C#) for more information.

Rob Windsor
  • 6,545
  • 1
  • 18
  • 24
0

Can try:

var lstQ_Buffer = new List<Q_Buffer>();

Get

lstQ_Buffer = unitOfWork.Q_BufferRepository.Get().ToList();

Then apply where

if (lstQ_Buffer.Count > 0)
{
    lstQ_Buffer = lstQ_Buffer.Where(q => q.fkProgramId == programId && q.fkYearId == yearId && q.fkSemesterId == semesterId && q.fkCourse_ModuleId == courseModuleId && q.fkSubject_SpecialtyId == subjectSpecialtyId && q.fkSubSpecialtyId == subSpecialtyId && q.fkTopicId == topicId && q.fkSubTopicId == subTopicId && q.fkDifficultyLevelId == diffucultyLevelId).ToList();
}
Sailendra
  • 1,318
  • 13
  • 25