无法将ICollection<t>转换为IEnumerable<t>。

4

我正在构建表达式树:

{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


@Adriani6,我们的问题在某些情况下有所不同: 1)重点是从IEnumerable转换为ICollection(我的情况:反之亦然) 2)他们试图转换实际数据集 - 在我的情况下,我需要正确类型的表达式。 - AlexZholob
你说得对,我已经撤回了我的投票 :) - Adrian
1
不,你不是在尝试将 ICollection<T> 转换为 IEnumerable<T>。你正在尝试转换(手摆两下)将生成 ICollection<T>委托。你不需要对 进行强制转换,而是需要在它生成一个结果时对其进行强制转换,这表明你将要编写(部分)表达式树来实现你想要的功能(如果这是你想走的路线)。 - Damien_The_Unbeliever
@Damien_The_Unbeliever 没错,你说得对。只需要将结果类型转换即可。 - AlexZholob
@DanielLoudon lambda表达式不具有像“select”这样的扩展方法,也没有Expression<Func<T, IEnumerable<K>>>。 - AlexZholob
1个回答

1

经过几个小时的研究和尝试不同的方法,我想出了一个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);

我其实没有找到解决方案,但如果有人遇到类似的问题,也许这个答案可以节省他的时间。


我无法使用你的解决方法,但是我必须向你致敬,因为你回来与我们分享了你的发现! - hasse

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接