komodosp
komodosp

Reputation: 3646

Get return value from function call within lambda expression

Consider the following C# line:

var item = listOfItems.FirstOrDefault(i => GetResult(i) <= upperLimit);

My question is, is there a way of getting the return value of GetResult(i) from within that line?

The obvious answer is have two lines:

var item = listOfItems.FirstOrDefault(i => GetResult(i) <= upperLimit);
var result = GetResult(item);

But it seems a bit inefficient to call the same function twice... Is a way have the result with just one call?

Upvotes: 2

Views: 1655

Answers (2)

Thomas Ayoub
Thomas Ayoub

Reputation: 29451

You can use this (assuming GetResult returns an int):

int? result = null;
var item = listOfItems.FirstOrDefault(x => (result = GetResult(x)) <= upperLimit);

This solution will keep the lazyness of FirstOrDefault : it will stop at first match found.

Upvotes: 2

Yacoub Massad
Yacoub Massad

Reputation: 27871

You can select both the item and the result of invoking GetResult on the item in an anonymous type to get them both like this:

var itemAndResult = listOfItems
    .Select(x => new {Item = x, Result = GetResult(x)})
    .Where(a => a.Result <= upperLimit)
    .FirstOrDefault();

var item = itemAndResult.Item;
var result = itemAndResult.Result;

Upvotes: 2

Related Questions