Charles-Alexandre Lafond Charles-Alexandre Lafond - 3 months ago 24
C# Question

Linq + Single line condition

Here is a piece of code:

var test = myListOfItems.Select(x => MyMethodReturningObject(x.SubItems) != null ? theValue : x.SubItems[0])


I would like that if MyMethodReturningObject returns an object, I assign the return value to theValue.

A bit like this:

var test = myListOfItems.Select(x => MyFunctionReturningObject(x.SubItems) != null ? MyMethodReturningObject(x.SubItems): x.SubItems[0])


But without calling the method twice.

Is this possible via Linq?

Thank you!

Answer
var test = myListOfItems.Select(x => MyFunctionReturningObject(x.SubItems) ?? x.SubItems[0])