zaitsman
zaitsman

Reputation: 9499

Return an IQueryable<dynamic> to filter in the parent method

For example, I have this code:

      IQueryable<MyModel> q = new List<MyModel>().AsQueryable(); // this is just an example, this is obviously not a list

      var query = from item in q select new { item.Property };

      var oneItem = query.FirstOrDefault(x => x.SomeProperty == somevalue);
      var allItems = query.ToArray();

Now in a bit more complex situation, I need to get oneItem and allItems in two different methods. So to follow DRY, i'd like to move my query to a private method and then in the consuming ones just call this.GetQuery().FirstOrDefault() or .ToArray() as required.

However, when I try to have the method as IQueryable<dynamic> I get the 'An expression tree may not contain a dynamic operation' error. If I change it to IQueryable<object> then my filtering in the oneItem doesn't work.

Upvotes: 2

Views: 4128

Answers (2)

Nick H
Nick H

Reputation: 154

For two methods to communicate they must understand the same type so you really want to project into a named type.

If you insist on using dynamic programming it can be done but you will need a lot of casting because dynamic is not a type but just a way of treating object:

IQueryable<MyModel> q = new List<MyModel>().AsQueryable(); // this is just an example, this is obviously not a list

      IQueryable<object> query = from item in q select (object)new { item.Property };

      var oneItem = query.FirstOrDefault(x => ((dynamic)x).SomeProperty == somevalue);
      object[] allItems = query.ToArray();

Upvotes: 0

Luthervd
Luthervd

Reputation: 1406

You need to return

IQueryable<MyObject>

You can make your methods/classes dry by using genrics eg

IQuerable<T> GetQueryable()

Then the consumer can specify what T should be and your away.

You can't use dynamic with linq. See here to understand why.

Upvotes: 2

Related Questions