C# Declare variable in lambda expression

后端 未结 3 540
轮回少年
轮回少年 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:35

    You can use the Select operator:

    IList 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);
    

提交回复
热议问题