0

I have an example where I want a IQueryable to convert to an IEnumerable (in order to use a multi-statement lambda), and then I immediately want to convert back to a IQueryable to use an extension method that requires IQueryable.

This is within a LINQ query if that matters?

My question is whether this can be time or space intensive? Or, more plainly, should I avoid it for any reason?

Here is the use case of this scenario:

var messageTimelines = ctx.UserMessageTimelines.AsEnumerable()
    .Where(w =>
    {
        var intersectCount = w.MessageTimelineParticipants.Intersect(timelineParticipants).Count();
        return ((intersectCount == w.MessageTimelineParticipants.Count()) && (intersectCount == timelineParticipants.Count()))
            ? true : false;
    }).AsQueryable().ProjectTo<MessageTimeline>(mapper.ConfigurationProvider);

As you can see I started off as a IQueryable and converted to 'AsEnumerable()' in order to utilize a multi-statement lambda. I then converted back to 'AsQueryable()' in order to use an AutoMapper extension method called 'ProjectTo', which requires 'IQueryable'.

To Note:

Evan Sevy
  • 659
  • 1
  • 13
  • 25
  • You should check what SQL is being generated. The code looks quite tricky. So it could be that you won't be happy with the final SQL query. – Vlad DX Aug 21 '19 at 20:48
  • @RufusL If I don't use 'AsEnumerable()' before the where clause, I get the following error: "A lambda expression with a statement body cannot be converted to an expression tree.". Strangely enough if I try replacing that with '.AsQueryable()' I get the same error. This 'SO' post, gave me the idea to use .AsEnumerable() - https://stackoverflow.com/a/15039292/230128 – Evan Sevy Aug 21 '19 at 20:54
  • 1
    That happens because Entity Framework can't convert your complex lambda to SQL. So, I guess, you'll load the whole collection `UserMessageTimelines` to the memory and only after that will apply `.Where()`. Therefore, there is no point to convert it back to `IQueryable`. – Vlad DX Aug 21 '19 at 21:02

0 Answers0