'How to use dynamic Linq with List object

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'



Solution 1:[1]

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.

Solution 2:[2]

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"));
}

Solution 3:[3]

You have loadOptions={loadData('Parameter I want to pass')} but loadData requires you to pass it both a string and a valid function. It throws an error because there is no valid function. So you want something like

const validCallback = (options: defaultOptions) => {
    console.log("Hi, I'm a valid callback here were your options: " + defaultOptions); // Assuming defaultOptions type can be displayed
}
<AsyncSelect
   loadOptions={loadData('Parameter I want to pass', validCallback)}
   defaultOptions
   onChange={(e) => setLicensee(e.value)}
/>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abdullah Rana
Solution 2 Hintham
Solution 3 TrivialCase