2

以下代码循环resultSet并填充列表 a SomeTyperesultSet本身是具有两个属性的匿名类型

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

无法将类型为
“WhereSelectListIterator 2[AnotherType,System.Collections.Generic.List1[SomeType]]”的对象转换为类型“System.Collections.Generic.List`1[SomeType]”。

4

1 回答 1

3

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

只需.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(...)返回 an IEnumerable<T>,而不是 a List<T>,因此这与使用此方法时遇到的问题类型完全相同:

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

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

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

这样做:

return statusGroupMapper.Map(groupSet);
于 2013-07-17T11:47:20.033 回答