C# Declare variable in lambda expression

后端 未结 3 608
轮回少年
轮回少年 2021-01-04 03:53

I want to do a simple lambda expression like this:

IList list = GetSomeList();

MyEntity1 result = list.SingleOrDefault(         


        
3条回答
  •  灰色年华
    2021-01-04 04:30

    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.

提交回复
热议问题