How to build an IEnumerable.Contains() Expression?

I’m currently working with ASP Dynamic Data for the first time and I’m trying to build a filter. Our users have a need to locate items in a list based upon whether or not the item is a child of a selected parent (our items can have more than one parent).

The items in question are Segments and each Segment has a property called RouteIds, of type IEnumerable, which is a collection of all of the Segment’s parent Ids.

I’ve gotten to this point in overriding the GetQueryable method in my filter, but I keep getting exceptions thrown on the last line shown:

ConstantExpression ce = Expression.Constant(int.Parse(this.ddlRouteNames.SelectedValue));
ParameterExpression pe = Expression.Parameter(source.ElementType);
MemberExpression me = Expression.Property(pe, this.Column.Name);
var callExpression = Expression.Call(typeof(Enumerable), "Contains", new Type[] { me.Type }, ce, me);

The thought is that a user would select the appropriate Route from a DropDownList and then I’d check to see if the Segment’s RouteIds property contains that Route’s Id.

Any pointers on how to get this working?

Edit – Here is the exception:

No generic method ‘Contains’ on type ‘System.Linq.Enumerable’ is
compatible with the supplied type arguments and arguments. No type
arguments should be provided if the method is non-generic.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

There are two problems in your code:

  1. Your parameters are backwards. The first parameter has to be the collection, the second the item you’re searching for.
  2. Your type argument is IEnumerable<int>, when it should be just int.

So, the fixed code is:

var callExpression = Expression.Call(
    typeof(Enumerable), "Contains", new[] { typeof(int) }, me, ce);

But it seems all the parts of your expression are not actually dynamic, so maybe something like that following would work too:

Expression<Func<Segment, bool>> expression =
    s => s.RouteIds.Contains(int.Parse(this.ddlRouteNames.SelectedValue));


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x