我希望我的代码转换为lambda / linq表达式

时间:2018-06-19 04:30:48

标签: c# .net linq lambda

if (resourceinfo != null && resourceinfo.Products != null)
{
    foreach (var product in resourceinfo.Products)
    {
        if (product.relatedEntities != null)
        {
            for (int i = 0; i < product.relatedEntities.Length; i++)
            {
                if (product.relatedEntities[i].reference.Equals("CONT1234"))
                {
                    if (product.resources != null)
                    {
                        foreach (var item in product.resources)
                        {
                            if (item.resource != null && item.resource.resourceCharacteristics != null)
                            {
                                for (int j = 0; j < item.resource.resourceCharacteristics.Length; j++)
                                {
                                    var ele = item.resource.resourceCharacteristics;
                                    if (ele[j].name.ToLower().Contains(IMEI_VALUE_NAME))
                                    {
                                        imeiNo = respObj.resourceCharacteristics[0].value = ele[j].value;
                                        break; 
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
            }
        }
        break;
    }
}

我希望这是lambda表达式或linq查询格式。当我尝试在null或空时绑定到lambda表达式时,会出现错误:

  

未定义对象的实例

1 个答案:

答案 0 :(得分:1)

你的问题不是很清楚,但我能得到的最好的问题是:

var query =
(
    from product in resourceinfo?.Products ?? Enumerable.Empty<Product>().Take(1)
    from relatedEntity in product?.relatedEntities
    where relatedEntity.reference.Equals("CONT1234")
    from item in product?.resources.Take(1)
    from ele in item?.resource?.resourceCharacteristics
    where ele.name.ToLower().Contains(IMEI_VALUE_NAME)
    select ele.value
).Take(1);