1

我正在尝试调试一位开发人员编写的代码,而 LINQ 表达式使这项任务变得很痛苦。我不知道如何调试复杂的 LINQ 表达式,所以谁能告诉我没有它们的等效代码是什么?

instanceIdList.AddRange(
  strname.Instances
    .Where(z => instancehealthList.Find(y => y.InstanceId == z.InstanceId 
                                          && y.State == "InService") != null)
    .Select(x => x.InstanceId)
    .ToList()
  .Select(instanceid => new ServerObj(servertype, instanceid))
);

这也写得好吗?一般来说,这种 LINQ 是鼓励还是反对?

4

2 回答 2

5

使用循环重构查询看起来像这样:

var serverObjList = new List<ServerObj>();
foreach (var inst in strname.Instances)
{
    foreach (var health in instancehealthList)
    {
        if (inst.InstanceID == health.InstanceID && health.State == "InService") 
        {
            serverObjList.Add(new ServerObj(servertype, health.InstanceID));
            break;
        }
    }
}
于 2013-09-27T20:13:53.567 回答
2

Rather than rewrite it to a series of foreach loops, you could eagerly-execute the expression after each operation, allowing you to inspect the data-set at intermediate steps, like so:

List<var> soFar = strname.Instances.Where(z => instancehealthList.Find(y => y.InstanceId == z.InstanceId && y.State == "InService") != null).ToList();

List<Int64> soFar2 = soFar.Select( x => x.InstanceId ).ToList();

List<ServerObj> soFar3 = soFar2.Select( instanceId => new ServerObj(servertype, instanceid) ).ToList();

instanceIdList.AddRange( soFar3 );

Of course, I feel this Linq isn't well-written.

于 2013-09-27T20:17:22.427 回答