Can't convert ICollection to IEnumerable

c# expression expression-trees icollection ienumerable


I'm constructing an expression tree.

{x => x.principal_info.First().agent_for_property_info}

It works as intended.

Actually, I have to change it toIEnumerable in place ofICollection as shown here.

The effective approach is as follows:

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;

I discover a legitimate lambda expression in the phrase:

{x => x.principal_info.First().agent_for_property_info}

The casting I do:

var expRight = (Expression<Func<T, IEnumerable<K>>>)expression;

Exception made for me:

Unable to cast object of 
to type 

Knowing thatICollection receives fromIEnumerable Assuming it is a very simple problem to solve.

I did a lot of study, but I couldn't figure out how to castICollection<T> to IEnumerable<T> or even whether it is possible?

In reality, the compiler may automatically cast it since the following lines are correct:

var queryData1 = new QueryData<contact_info, IEnumerable<property_info>>()
                    WhereClause = expression,
                    SelectClause = info => info.principal_info.First().agent_for_property_info

Given that this phrase is one ofICollection :

info => info.principal_info.First().agent_for_property_info

9/3/2018 12:25:23 PM

Accepted Answer

After spending a few hours reading and experimenting with various strategies, I came up with an idea on how to deal with this exception. Therefore, the advice from the comments was the workaround I used:

x => x.principal_info.First().agent_for_property_info.Select(x4 => x4)

What I included when creating an expression is as follows:

var result1 = Expression.Call(
                    typeof(Enumerable), "Select", new Type[] { elementResultType, elementResultType },
                    resultProperty, resultExpr);

Although I didn't locate the answer, if someone runs into this issue, maybe my method can help him save time.

9/3/2018 3:02:28 PM

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow