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

Can't convert ICollection<t> to IEnumerable<t>

我正在构建表达式树:

{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

经过几个小时的研究,尝试不同的方法,我想出了一个想法,试图克服这个异常。所以我使用的解决方法是评论中的建议:

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

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