Home > database >  How to use dynamic Linq with List object
How to use dynamic Linq with List object

Time:05-19

I have List object of type dynamic like List<dynamic> but when I try to use it with Linq then it's not working. Below is my Linq syntax

var tt = lst.Where(x => (string)x.Type == "test");

So how can I use dynamic Linq on List having type as dynamic object.

It throws an error:

'System.Collections.Generic.List<object>' does not contain a definition for 'Type'

CodePudding user response:

Make sure you have declared the dynamic type correctly or is there any mismatch between the objects. I just tried the same thing and it works for me.

dynamic obj = new {
    Data = "sjds"
};

dynamic obj2 = new {
    Data = "sjdsf"
};

List<dynamic> dynamics = new List<dynamic>();
dynamics.Add(obj);
dynamics.Add(obj2);

var str = dynamics.Where(x => x.Data == "sjds");

If your case different than this you can share the full code to better understand the scenario.

CodePudding user response:

The compiler has no way to know what your dynamic objects look like. Therefore you need to tell the compiler by casting to a type. Since you're assuming that a particular property exists on your dynamic object (Type), you can try and cast it.

List<YourType> yourList = lst as List<YourType>;
if (yourList!=null){
  var filtereList = yourList.Where(x=>x.Type.Equals("test"));
}
  • Related