无法转换ICollection 到IEnumerable

问题描述 投票:3回答:1

我正在构建表达式树:

{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

c# expression ienumerable expression-trees icollection
1个回答
1
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.