如何在动态列表中使用Select?

How to use Select in dynamic list?

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?

您需要将 dynamic reqList= new List<dynamic>(); 更改为 List<dynamic> reqList= new List<dynamic>();dynamic 对象中,方法绑定是在运行时完成的,而不是在编译时。您必须像这样投射列表项:

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

更多关于 dynamic - https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/using-type-dynamic

要点是 reqList 在您的代码中不是 IEnumerable。只需将签名更改为动态列表即可。

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();