【问题标题】:I want my code to convert into lambda / linq expression [closed]我希望我的代码转换为 lambda / linq 表达式 [关闭]
【发布时间】:2018-06-19 04:30:47
【问题描述】:
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 查询格式。当我尝试绑定到 lambda 表达式时,只要有 null 或空,就会出现错误:

对象的实例未定义

【问题讨论】:

  • 并非所有东西都需要 LINQ。如果您尝试将其转换为 LINQ 并且出现问题,您应该展示您的工作。
  • 我认为你不需要 LINQ,但你肯定需要重构你的代码。我的建议是定义更多方法来处理每种对象类型。
  • 你真的是在做双重分配imeiNo = respObj.resourceCharacteristics[0].value = ele[j].value 还是这意味着别的什么?
  • 变量imeiNo & respObj 没有在任何地方定义。这使得在这里知道做什么变得有点困难。

标签: c# .net linq lambda


【解决方案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);

【讨论】:

  • 感谢 Enigmativity.. 你让我很开心.. 真的你是天才....再次感谢
猜你喜欢
  • 1970-01-01
  • 2019-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-29
  • 2019-12-18
  • 2010-12-04
相关资源
最近更新 更多