Home > Back-end >  How to use Select in dynamic list?
How to use Select in dynamic list?

Time:12-29

I have dynamic models in my dynamic list. attributes.blabla exist on all my models.

        dynamic reqList= new List<dynamic>();
        
        //filled this list

        List<string> blablaList = reqList.Select(x => x.attributes.blabla).ToList();

I am taking this error

How can i take attributes.blabla as string list?

CodePudding user response:

The main point is that reqList is not IEnumerable in your code. Just change the signature to List of dynamics.

List<dynamic> reqList= new List<dynamic>();
reqList.Add(new{ attributes = new{blabla = "qq"}});

List<string> blablaList = reqList.Select(x => x.attributes.blabla as string).ToList();

CodePudding user response:

You need to change dynamic reqList= new List<dynamic>(); to List<dynamic> reqList= new List<dynamic>(); In dynamic object, the method binding is being done at runtime, not at compile time. You have to cast the list items like this:

List<string> blablaList = reqList.Select(x => x.attributes.blabla).Cast<string>().ToList();

More about dynamic - https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/using-type-dynamic

  • Related