1

I have a list and a query simply defined as this:

var list = new List<int>();

for (var i = 0; i < 4; i++)
{
    list.Add(i);
}

var query = list.AsQueryable();

Now I have an Expression which returns the square of the number:

private static Expression<Func<int, int>> Square()
{
    return i => i * i;
}

and the third power like this:

private static Expression<Func<int, int>> Third()
{
    return i => i * i * i;
}

What I want is to be able to select the sum of these in the Select expression with a code similar to this pseudocode:

var result = query.Select(Square() + Third()).ToList();

I expect the result to be

0
2
12
36

Is there a way to easily achieve that or I should do it some other way?

P.S. keep in mind, the methods are simplified to stress for ease of defining the issue.

P.S. I am using expressions because this is oversimplified example of the Linq-to-entities issue and I understood that I can only use IQueryable as of this topic.

Andrius Naruševičius
  • 8,348
  • 7
  • 49
  • 78
  • 4
    That should be called `Cube()`, not `Third()`. – SLaks Jun 09 '14 at 20:51
  • Apparently I forgot to include that I will use this for linq to entities ;( According to http://blogs.msdn.com/b/meek/archive/2008/05/02/linq-to-entities-combining-predicates.aspx I have to use expressions. At the moment I am feeling stupid for oversimplifying the issue. Or maybe I am wrong and you can manage to complete the task without Expressions? – Andrius Naruševičius Jun 09 '14 at 20:56
  • If you want to make it an entity query, you do need expressions, and that changes the way the answer can work. – SLaks Jun 09 '14 at 20:57
  • I think the http://stackoverflow.com/questions/457316/combining-two-expressions-expressionfunct-bool covers combining (also it shows specific bool case). If not - search for other "[C#] expression combine" questions first and comment why this is different. – Alexei Levenkov Jun 09 '14 at 21:01

1 Answers1

1

If you need expression trees, use Expression.Add static method on Square().Body and Third().Body.

If you just need delegates, use x => Square().Compile()(x) + Third().Compile()(x).

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181