Converting a LINQ clause to a dynamic LINQ clause

c# dynamic-linq

Question

I intend to move 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 a few different things (AsQueryable , Where<SomeData> I can get the first form to build, but not the second.

I'm not really familiar with the generic extension techniques in C#. The<Tsource> does not make sense to me, which may be the issue. I also don't know why I can type..Where() as soon as IntelliSense just shows.Where<> a universal. I anticipate seeing a second.Where I regret not having it sans the generic sign.

Class

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

UPDATE
Where() use seems to be a little unclear, which may or may not be my fault. I have a related inquiry, please. This response indicates that the where clause's usage of the property name is allowed. The property must continue to be a string. That's what I need, so if that means dynamic LINQ is necessary, so be it.

1
3
5/23/2017 11:48:50 AM

Accepted Answer

I was able to make the conversion work with your assistance.

  1. Put Dynamic LINQ in place (I used NUGET. Look up System.Linq.Dynamic online.
  2. Add using System.Linq.Dynamic
  3. Questions should take the form of

        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 Sample library for C# by ScottGU; it is beneficial. (VB) (Original Article)

2
3/21/2012 7:28:51 PM

Popular Answer

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

The Where You must supply a delegate or lambda since method expects a delegation, not a string.

You will need to utilize Reflection to make the property value lookup dynamic, according to your remark in one of the earlier responses.

It seems that you must independently install the Dynamic Linq library (Get the source code.), however.



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