【发布时间】: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