Converting a LINQ clause to a dynamic LINQ clause

c# dynamic-linq


I want to go from

        var selectData = (from i in data
                          where i.Name == "Bob1"
                          select i);


        var selectData = (from i in data
                          select i).Where("Name==Bob1");

I've tried various approaches (AsQueryable, Where<SomeData>), but can't get the second form to compile.

I do not have a good grasp on C#'s generic extension methods. The <Tsource> doesn't make sense to me so that could be the problem. Also, I do not understand why I can type .Where() when intellisense only displays .Where<> (a generic). I expect to see a second Where without the generic symbol...alas I do not.


public class SomeData
    public string Name { get; set; }
    public string Address { get; set; }

There appears to be some confusion as to how Where() can be used that may well be my fault. Please see a related question. Based off this answer, the property name in the where clause is perfectly legal. I need the property to remain a string. If that means dynamic LINQ is required, then so be it...that's what I need.

5/23/2017 11:48:50 AM

Accepted Answer

With all your help I have managed to get the conversion to function.

  1. Install Dynamic LINQ (I used NUGET. Search online for System.Linq.Dynamic)
  2. Add using System.Linq.Dynamic
  3. Query should be of the form

        var selectData = (from i in data
                          select i).AsQueryable().Where("Name = @0","Bob1");//@0 is called an identifier.  "Name = Bob1" straight up fails.
  4. Install ScottGU's C# sample helps. (VB) (Original Post)

3/21/2012 7:28:51 PM

Popular Answer

var selectData = (from i in data
                  select i).Where(datum => datum.Name == "Bob1");

The Where method takes a delegate, not a string, so you need to pass in a delegate or lambda.

Edit: based upon your comment to one of the other answers, you will need to use Reflection to make the property value lookup dynamic.

Edit: looks like you need to download the source code for the Dynamic Linq library separately.

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow