To the best of my knowledge, there is no practical difference between the two (and the second might get optimized to the first). There's also no difference between doing this with LINQ and with a regular function.
However, the second one will be easier to debug, because you're putting the result somewhere after evaluating it, so you can put a breakpoint in and examine that variable. I find the first marginally clearer, though.
Here's two functions:
int Foo(int a, int b)
{
int x = a+b;
return x;
}
int Bar(int a, int b)
{
return a+b;
}
And here's the IL that's generated with optimizations off (according to LINQPad):
Foo:
IL_0000: nop
IL_0001: ldarg.1
IL_0002: ldarg.2
IL_0003: add
IL_0004: stloc.0 // x
IL_0005: ldloc.0 // x
IL_0006: stloc.1 // CS$1$0000
IL_0007: br.s IL_0009
IL_0009: ldloc.1 // CS$1$0000
IL_000A: ret
Bar:
IL_0000: nop
IL_0001: ldarg.1
IL_0002: ldarg.2
IL_0003: add
IL_0004: stloc.0 // CS$1$0000
IL_0005: br.s IL_0007
IL_0007: ldloc.0 // CS$1$0000
IL_0008: ret
You'll notice that Foo
has two extra lines where it declares the variable then reads it.
And here it is with optimizations on:
Foo:
IL_0000: ldarg.1
IL_0001: ldarg.2
IL_0002: add
IL_0003: stloc.0 // x
IL_0004: ldloc.0 // x
IL_0005: ret
Bar:
IL_0000: ldarg.1
IL_0001: ldarg.2
IL_0002: add
IL_0003: ret
Again, one extra assignment and load. You'll never notice the difference.