4
//Data is IList<ExpandoObject>
var result = (from dynamic item in Data
              where item.id== "123"
              select item).FirstOrDefault();

Want to achieve below feature but it is erroring out by saying remove not available for dynamic objects.

Data.Remove(result);

Let me know if any suggestions. thanks

גלעד ברקן
  • 23,602
  • 3
  • 25
  • 61

1 Answers1

3

Error: remove not available for dynamic objects

base on Microsoft's docs, The Remove method of IList<T> accepts a parameter with the type of T:

ICollection<T>.Remove(T)

In your example, T is an ExpandoObject, so it means in the Remove method you should pass a parameter with the type of ExpandoObject but you didn't and you are passing a parameter with the type of dynamic. Therefore you facing this error

for resolving this you have two way:

1) Use explicit type instead of var:

ExpandoObject result = ...

2) cast the result when you are passing it to Remove:

Data.Remove((ExpandoObject) result)

I think with doing one of these ways, your problem will resolve. good luck.

Hamed Moghadasi
  • 1,523
  • 2
  • 16
  • 34
  • 1
    The LINQ expression is casting `ExpandoObject` to `dynamic`, so as part of declaring `result` as `ExpandoObject` (#1), you would have to cast the result of the LINQ expression back to `ExpandoObject`. #2 is probably easier to understand at a glance and is correct without modification. – madreflection Feb 19 '20 at 21:50
  • _"so it means in the Remove method you should pass a parameter with the type of ExpandoObject but you didn't and you are passing a parameter with the type of dynamic"_ I'm not sure this is strictly accurate. The point of `dynamic` is exactly so that it can be passed instead of anything and that it gets resolved at run time. Note, that this (OP) works perfectly in .net 3.0, so I suspect that this is just a framework bug that got fixed in .net core. – Andrew Savinykh Feb 20 '20 at 00:28
  • See my comment to the OP for the original bug. – Andrew Savinykh Feb 20 '20 at 06:26