IEnumreable dynamic and lambda

♀尐吖头ヾ 提交于 2020-01-03 19:08:15

问题


I would like to use a lambda expression on a IEnumerable<dynamic> type, howerver im getting the following error on attributes and coordinates where im using a new lambda expression:

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

Here is my code

public static object returnFullSelectWithCoordinates(IEnumerable<dynamic> q)
        {
            return q.Select(b => new
            {
                route_id = b.b.route_id,
                name = b.b.name,
                description = b.b.description,
                attributes = b.b.route_attributes.Select(c => c.route_attribute_types.attribute_name),
                coordinates = b.b.coordinates.Select(c => new coordinateToSend { sequence = c.sequence, lat = c.position.Latitude, lon = c.position.Longitude })

            });

Is there any workaround to make my method work?


回答1:


Since Select<> is an extension method, it won't work on dynamic types.

You can get the same result by using Enumerable.Select<>.

Try this query:

Enumerable.Select(q,(Func<dynamic,dynamic>)(b => new
        {
            route_id = b.b.route_id,
            name = b.b.name,
            description = b.b.description,
            attributes = b.b.route_attributes.Select(c => c.route_attribute_types.attribute_name),
            coordinates = b.b.coordinates.Select(c => new coordinateToSend { sequence = c.sequence, lat = c.position.Latitude, lon = c.position.Longitude })

        });


来源:https://stackoverflow.com/questions/15385260/ienumreable-dynamic-and-lambda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!