Using LINQ with dynamic variables in C#

982 Views Asked by At

Is this the right way to use dynamic variables in C#?

I am getting the below error when i try to use LINQ expressions with dynamic variable..

Error - Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic dAnimal = new Animal();
            string cc = dAnimal.x;
            Animal oAnimal = new Animal();
            var test1 = oAnimal.listFood.Where(a => a.foodName == "");
            var test2 = dAnimal.listFood.Where(a => a.foodName == "");//Error
        }
    }

    public class Animal
    {
        public string animalName {get; set;};
        public List<Food> listFood;
    }

    public class Food
    {
        public string foodName;
    }
}
1

There are 1 best solutions below

0
On

My understanding of the problem is that dAnimal.listFood type is unknown at compilation time, because dAnimal is dynamic. So compiler can't guarantee, that listFood is IEnumerable and it's item has foodName property. However, if you will use delegate, every listFood item will implicitly be casted to type of delegate input parameter (you will still have a problem with collection type).

Any way, there is no any need to use dynamic in this context.