Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Where from LINQ clause to dynamic LINQ

I want to go from

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

To

        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.

Class

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

UPDATE
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.

like image 904
P.Brian.Mackey Avatar asked Dec 05 '25 08:12

P.Brian.Mackey


1 Answers

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.

like image 193
Paul Ruane Avatar answered Dec 07 '25 21:12

Paul Ruane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!