c# - 无法转换 ICollection到 IEnumerable
问题描述
我正在构建表达式树:
{x => x.principal_info.First().agent_for_property_info}
它按预期工作。
事实上,我需要将其转换为IEnumerable
而不是ICollection
如您在此处看到的那样。
这是有效的方法:
public Expression<Func<T, IEnumerable<K>>> GetGenericExpression<T, K>(bool first = false, params string[] properties)
{
var expression = GetNavigationPropertySelector<T, K>(typeof(T), first, properties);
var expRight = (Expression<Func<T, IEnumerable<K>>>)expression;
return expRight;
}
在表达式中,我得到了有效的 lambda 表达式:
{x => x.principal_info.First().agent_for_property_info}
当我铸造时:
var expRight = (Expression<Func<T, IEnumerable<K>>>)expression;
我得到一个例外:
Unable to cast object of
type
'System.Linq.Expressions.Expression`1[System.Func`2[SomeModel1,
System.Collections.Generic.ICollection`1[SomeModel]]]'
to type
'System.Linq.Expressions.Expression`1[System.Func`2[SomeModel1
,System.Collections.Generic.IEnumerable`1[SomeModel]]]'.
我知道这ICollection
继承自IEnumerable
假设,它很容易修复。
我进行了很多研究,但没有找到解决方案如何投射ICollection<T>
或者IEnumerable<T>
这是否可能?
事实上,编译器可以隐式转换它,因为这些行是有效的:
var queryData1 = new QueryData<contact_info, IEnumerable<property_info>>()
{
WhereClause = expression,
SelectClause = info => info.principal_info.First().agent_for_property_info
};
因为这个表达式是一种类型ICollection
:
info => info.principal_info.First().agent_for_property_info
解决方案
经过几个小时的研究,尝试了不同的方法,我想出了 Idea,试图克服这个例外。所以我使用的解决方法是评论中的建议:
x => x.principal_info.First().agent_for_property_info.Select(x4 => x4)
这是我在构建表达式时添加的内容:
var result1 = Expression.Call(
typeof(Enumerable), "Select", new Type[] { elementResultType, elementResultType },
resultProperty, resultExpr);
我实际上没有找到解决方案,但如果有人遇到这样的问题,也许这个答案可以节省他的时间。
推荐阅读
- c# - 如何在不对类进行硬编码的情况下将类传递给泛型?
- python - 在 azure devops 中将单元和集成测试设置为基于 python 的 azure 函数的正确方法
- javascript - 单击行的展开按钮时,Datatables row.data() 返回未定义
- r - Rstudio 查看器窗格一直在自包含文档中查找 index.html
- acumatica - 有没有办法在当前 BLC 之外获取通过 PXLongOperation() 执行的特定线程的状态?
- xml - 在重复元素中扩展重复元素
- c - 为什么列表中的这个搜索功能不起作用?
- python - 如何在 .py 中设置 .kv 中可选标签的文本
- python - 如何找到工作区名称?
- express - Apollo GraphQL 游乐场:401 未经授权