Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Declare variable in lambda expression

Tags:

c#

lambda

linq

I want to do a simple lambda expression like this:

IList<MyEntity1> list = GetSomeList();

MyEntity1 result = list.SingleOrDefault<MyEntityList>(
    e => GetMyEntity2(e) != null && GetMyEntity2(e).Id != null && GetMyEntity2(e).Id > 0
);

That works perfectly, but getting MyEntity2 from MyEntity1 is not so simple so I would like to declare a variable into the lambda expression to save MyEntity2 and use it, instead of calling again and again to GetMyEntity2 method. Is that possible?

Note: The code is just an example that reflects my real case.

Thanks!

like image 967
Diego Avatar asked Jun 15 '11 19:06

Diego


3 Answers

Well, first off, are you trying to use this in linq to sql / entity framework / other?

If not, then just do this

list.SingleOrDefault(e => {
   var entity = GetMyEntity2(e);

   return entity != null && entity.Id != null && entity.Id > 0;
});
like image 116
Darren Kopp Avatar answered Oct 08 '22 13:10

Darren Kopp


If you want to use the "query comprehension" syntactic form you can do this:

var query = from entity1 in list
            let entity2 = GetMyEntity2(entity1)
            where entity2 != null
            where entity2.Id != null 
            where entity2.Id > 0
            select entity1;
var result = query.SingleOrDefault();

Note also that the middle "where" clause might not be necessary. If "entity2.Id" is a nullable int then it will be correctly checked for null by the lifted > operator.

like image 36
Eric Lippert Avatar answered Oct 08 '22 15:10

Eric Lippert


You can use the Select operator:

IList<MyEntity1> list = GetSomeList();

MyEntity1 result = list
    .Select(x => new { Item = x, Entity2 = GetMyEntity2(x) })    
    .SingleOrDefault(x => x.Entity2 != null && x.Entity2.Id != null && x.Entity2.Id > 0);

Or, since you're not even using the Item after pushing it through GetMyEntity2 you could just have:

MyEntity1 result = list
    .Select(x => GetMyEntity2(x))    
    .SingleOrDefault(x => x != null && x.Id != null && x.Id > 0);
like image 32
Kirk Woll Avatar answered Oct 08 '22 13:10

Kirk Woll