【问题标题】:Methods with anonymous and dynamic type throwing error具有匿名和动态类型抛出错误的方法
【发布时间】:2013-07-17 11:42:46
【问题描述】:

以下代码循环通过resultSet 并填充SomeType 的列表a。 resultSet 本身是一个匿名类型,有两个属性

var resultSet = SomeCollection.Select(x => new {
    FirstProp = x,
    SomeMembers = SomeLinkCollection.Where(l => l.SomeId == x.SomeId)
                                    .Select(l => AnotherCollection[l.Id])
});

var result = new List<SomeType>();
foreach (var currentGroup in resultSet) {
    result.Add(new SomeType {
        Prop1 = currentGroup.Item.Id,
        Prop2 = currentGroup.Item.Name,
        Prop3 = currentGroup.SomeMembers.OrderBy(x => x.Name)
    });
}

要删除设置新的Sometype 实例,我使用动态类型创建了一个映射器类/接口来拆分职责并使用依赖注入:

public class SomeMapper : ISomeMapper {
    public List<SomeType> Map(dynamic resultSet) {
        return resultSet.Select(new SomeType {
            Prop1 = currentGroup.Item.Id,
            Prop2 = currentGroup.Item.Name,
            Prop3 = ((IEnumerable<AnotherType>)resultSet.SomeMembers)
                                                .OrderBy(x => x.Name)
        });
    }
}

所以上面的代码变成了:

return resultSet.Select(SomeMapper.Map);

错误

不能隐式转换类型 'System.Collections.Generic.IEnumerable>' 到“System.Collections.Generic.List”。显式转换 存在(您是否缺少演员表?)

我尝试了一些显式转换为 SomeType 的技巧,但它在运行时失败了

return (List<SomeType>)groupSet.Select(statusGroupMapper.Map);

无法转换类型的对象
'WhereSelectListIterator2[AnotherType,System.Collections.Generic.List1[SomeType]]' 输入“System.Collections.Generic.List`1[SomeType]”。

【问题讨论】:

    标签: c# dependency-injection ienumerable


    【解决方案1】:

    您需要创建一个结果列表。

    只需在您的表达式后添加.ToList()

    public class SomeMapper : ISomeMapper {
        public List<SomeType> Map(dynamic resultSet) {
            return resultSet.Select(new SomeType {
                Prop1 = currentGroup.Item.Id,
                Prop2 = currentGroup.Item.Name,
                Prop3 = ((IEnumerable<AnotherType>)resultSet.SomeMembers).OrderBy(x => x.Name)
            }).ToList();
        }
    }
    

    .Select(...) 返回一个IEnumerable&lt;T&gt;,而不是List&lt;T&gt;,所以这与使用此方法会遇到的问题完全相同:

    public string Name()
    {
        return 10; // int
    }
    

    你调用的时候也有问题,别这样:

    return (List<SomeType>)groupSet.Select(statusGroupMapper.Map);
    

    这样做:

    return statusGroupMapper.Map(groupSet);
    

    【讨论】:

    • 感谢您的回复,我尝试使用 .ToList() 但同样的错误仍然存​​在输入“System.Collections.Generic.List`1[SomeType]”。
    • 你还在施法,请移除施法。
    • 删除强制转换会给我编译时错误 错误 61 无法将类型 'System.Collections.Generic.IEnumerable>' 隐式转换为 'System.Collections.Generic。列表'。存在显式转换(您是否缺少演员表?)
    • 您需要致电.ToList(),正如答案中所指出的那样。难道你不能简单地复制我的代码,看看它是否有效,而不是修改你自己的吗?
    • 我确实调用了 .ToList() 我也尝试粘贴您的答案,但没有显式转换编译时错误(如上所述)仍然存在。
    猜你喜欢
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多