如何简化多个嵌套的foreach循环?

时间:2018-11-07 12:59:36

标签: c# wpf foreach datagrid

 private DataTable GetAttributeTable()
    {
        DataTable cltAttributeTable = new DataTable("CLT_ATTRIBUTE");
        DataColumnCollection iRefColumns = cltAttributeTable.Columns;
        //BETHiddenColumn is defined for hiding certain columns at the UI
        //And can be used for manipulating entities internally
        iRefColumns.AddRange(new[]
        {
            new BETHiddenColumn { ColumnName = CLDConstants.CLTGUID, DataType = typeof(string), ReadOnly = true },
            new DataColumn { ColumnName = CLDConstants.CLTNAME, DataType = typeof(string), ReadOnly = true },
            new BETHiddenColumn { ColumnName = CLDConstants.SHEETID, DataType = typeof(string), ReadOnly = true },
            new DataColumn { ColumnName = CLDConstants.SHEETNAME, DataType = typeof(string), ReadOnly = true },
            new DataColumn { ColumnName = "OBJECT_TYPE", DataType = typeof(string), ReadOnly = true },
            new DataColumn { ColumnName = "OBJECT_NAME", DataType = typeof(string), ReadOnly = true },
            new DataColumn { ColumnName = "ATTRIBUTE_NAME", DataType = typeof(string), ReadOnly = true },
            new DataColumn { ColumnName = "ATTRIBUTE_VALUE", DataType = typeof(string), ReadOnly = false }
        });
        return cltAttributeTable;
    }

public override async Task<DataTable> GetDataAsync(ControlNetworkStructure controlNetwork)
    {
        DataTable cltAttributeTable = GetAttributeTable();
        try
        {
            using (var automationService = ConsumedServiceProvider.Provider.AutomationService)
            {
                foreach (string userDefinedLogicTemplate in selectedCLT)
                {
                    var controlLogicClt =
                        automationService.AutomationClt.GetControlLogicTemplate(userDefinedLogicTemplate);
                    foreach (ISheet sheet in await controlLogicClt.GetSheets())
                    {

                        foreach (IFunctionCode functionCode in await sheet.GetFunctionCodes())
                        {
                            foreach (IHarmonyAttribute functionCodeAttribute in functionCode.Attributes)
                            {

                                DataRow row = GetRow(cltAttributeTable, controlLogicClt, sheet);
                                row["OBJECT_TYPE"] = "FUNCTION CODE";
                                row["OBJECT_NAME"] = functionCode.Name;
                                row["ATTRIBUTE_NAME"] = functionCodeAttribute.Type;
                                row["ATTRIBUTE_VALUE"] = functionCodeAttribute.Value;
                                cltAttributeTable.Rows.Add(row);
                            }
                        }

                        foreach (IInputReference inputReference in await sheet.GetInputReferences())
                        {
                            foreach (IHarmonyAttribute functionCodeAttribute in inputReference.Attributes)
                            {

                                DataRow row = GetRow(cltAttributeTable, controlLogicClt, sheet);
                                row["OBJECT_TYPE"] = "IREF";
                                row["OBJECT_NAME"] = inputReference.Name;
                                row["ATTRIBUTE_NAME"] = functionCodeAttribute.Type;
                                row["ATTRIBUTE_VALUE"] = functionCodeAttribute.Value;
                                cltAttributeTable.Rows.Add(row);
                            }
                        }

                        foreach (IOutputReference outputReference in await sheet.GetOutputReferences())
                        {
                            foreach (IHarmonyAttribute functionCodeAttribute in outputReference.Attributes)
                            {

                                DataRow row = GetRow(cltAttributeTable, controlLogicClt, sheet);
                                row["OBJECT_TYPE"] = "OREF";
                                row["OBJECT_NAME"] = outputReference.Name;
                                row["ATTRIBUTE_NAME"] = functionCodeAttribute.Type;
                                row["ATTRIBUTE_VALUE"] = functionCodeAttribute.Value;
                                cltAttributeTable.Rows.Add(row);
                            }
                        }

                        foreach (IText text in await sheet.GetTexts())
                        {
                            foreach (IHarmonyAttribute functionCodeAttribute in text.Attributes)
                            {

                                DataRow row = GetRow(cltAttributeTable, controlLogicClt, sheet);
                                row["OBJECT_TYPE"] = "TEXT";
                                row["OBJECT_NAME"] = text.Name;
                                row["ATTRIBUTE_NAME"] = functionCodeAttribute.Type;
                                row["ATTRIBUTE_VALUE"] = functionCodeAttribute.Value;
                                cltAttributeTable.Rows.Add(row);
                            }
                        }


                    }
                }
            }
        }
        catch (Exception exception)
        {
            LogService.LogException(this, ServiceResources.CONTEXT_CLD_EDITOR, "CLT Attribute",
                exception);
        }
        finally
        {
            // Accepting all the modification to the table before leaving this method call
            cltAttributeTable.AcceptChanges();
        }
        return cltAttributeTable;
    }

说明

我有一个内部有多个foreach循环的方法,因为我是C#的初学者,所以我很难理解它。我也读到在程序中编写多个foreach循环不是一个好习惯。 该方法返回一个数据表,并将其绑定到Datagrid。 谁能帮助我简化它,使其变得更易读和更直观?

2 个答案:

答案 0 :(得分:0)

如果IFunctionCode,IInputReference等的Attribute属性基于公共接口,则可以执行以下操作:

List<ICommomInterface> items = new List<ICommomInterface>();
items.AddRange(await sheet.GetFunctionCodes());
items.AddRange(await sheet.GetInputReferences());
items.AddRange(await sheet.GetOutputReferences());
items.AddRange(await sheet.GetTexts());

items.foreach(item =>
{
    item.Attributes.ForEach(attrib =>
    {
        DataRow row = GetRow(cltAttributeTable, controlLogicClt, sheet);
        if(item is IFunctionCode){
            row["OBJECT_TYPE"] = "FUNCTION CODE";
        } else if(_other types_)
        {
        }
        row["OBJECT_NAME"] = item.Name;
        row["ATTRIBUTE_NAME"] = attrib.Type;
        row["ATTRIBUTE_VALUE"] = attrib.Value;
        cltAttributeTable.Rows.Add(row);
    });
});

如果这是您的意图。 如果它们不共享公共基本接口,则必须使用对象类作为列表,并扩展if(item为IFunctionCode){...检查。

答案 1 :(得分:0)

好的,这很仓促,但是我认为这是一个好的开始。我没有时间对其进行测试,因此可能存在一些错误。另外,还有很大的改进空间。

private DataTable GetAttributeTable()
{
    DataTable cltAttributeTable = new DataTable("CLT_ATTRIBUTE");
    DataColumnCollection iRefColumns = cltAttributeTable.Columns;
    //BETHiddenColumn is defined for hiding certain columns at the UI
    //And can be used for manipulating entities internally
    iRefColumns.AddRange(new[]
    {
        new BETHiddenColumn { ColumnName = CLDConstants.CLTGUID, DataType = typeof(string), ReadOnly = true },
        new DataColumn { ColumnName = CLDConstants.CLTNAME, DataType = typeof(string), ReadOnly = true },
        new BETHiddenColumn { ColumnName = CLDConstants.SHEETID, DataType = typeof(string), ReadOnly = true },
        new DataColumn { ColumnName = CLDConstants.SHEETNAME, DataType = typeof(string), ReadOnly = true },
        new DataColumn { ColumnName = "OBJECT_TYPE", DataType = typeof(string), ReadOnly = true },
        new DataColumn { ColumnName = "OBJECT_NAME", DataType = typeof(string), ReadOnly = true },
        new DataColumn { ColumnName = "ATTRIBUTE_NAME", DataType = typeof(string), ReadOnly = true },
        new DataColumn { ColumnName = "ATTRIBUTE_VALUE", DataType = typeof(string), ReadOnly = false }
    });
    return cltAttributeTable;
}

public override async Task<DataTable> GetDataAsync(ControlNetworkStructure controlNetwork)
{
    DataTable cltAttributeTable = new DataTable();
    try
    {
        using (var automationService = ConsumedServiceProvider.Provider.AutomationService)
        {
            foreach (string userDefinedLogicTemplate in selectedCLT)
            {
                var controlLogicClt =
                    automationService.AutomationClt.GetControlLogicTemplate(userDefinedLogicTemplate);

                cltAttributeTable = await LoopDeLoop(controlLogicClt);
            }
        }
    }
    catch (Exception exception)
    {
        LogService.LogException(this, ServiceResources.CONTEXT_CLD_EDITOR, "CLT Attribute",
            exception);
    }
    finally
    {
        // Accepting all the modification to the table before leaving this method call
        cltAttributeTable.AcceptChanges();
    }
    return cltAttributeTable;
}

//Main loop with loops adding rows
private async Task<DataTable> LoopDeLoop(dynamic controlLogicClt)
{
    DataTable cltAttributeTable = GetAttributeTable();

    foreach (ISheet sheet in await controlLogicClt.GetSheets())
    {
        foreach (IFunctionCode functionCode in await sheet.GetFunctionCodes())
        {
            cltAttributeTable = GetNewRows(cltAttributeTable, functionCode.Attributes, functionCode.Name, "FUNCTION CODE", controlLogicClt, sheet);
        }

        foreach (IInputReference inputReference in await sheet.GetInputReferences())
        {
            cltAttributeTable = GetNewRows(cltAttributeTable, inputReference.Attributes, inputReference.Name, "IREF", controlLogicClt, sheet);
        }

        foreach (IOutputReference outputReference in await sheet.GetOutputReferences())
        {                           
            cltAttributeTable = GetNewRows(cltAttributeTable, outputReference.Attributes, outputReference.Name, "OREF", controlLogicClt, sheet);                        
        }

        foreach (IText text in await sheet.GetTexts())
        {
            cltAttributeTable = GetNewRows(cltAttributeTable, text.Attributes, text.Name, "TEXT", controlLogicClt, sheet);
        }
    }
}

//Adds the new created rows to the DataTable
private DataTable GetNewRows(DataTable cltAttributeTable, List<IHarmonyAttribute> attributes, string name, string objectType, dynamic controlLogicClt, ISheet sheet)
{
    foreach (IHarmonyAttribute attribute in attributes)
    {
        cltAttributeTable.Rows.Add(GetNewRow(sourceDataRow, attribute, name, objectType, controlLogicClt, sheet));
    }
}

//Creates and populates the new row
private DateRow GetNewRow(IHarmonyAttribute attribute, string name, string objectType, dynamic controlLogicClt, ISheet sheet)
{
        DataRow row = GetRow(cltAttributeTable, controlLogicClt, sheet);
        row["OBJECT_TYPE"] = objectType;
        row["OBJECT_NAME"] = name;
        row["ATTRIBUTE_NAME"] = attribute.Type;
        row["ATTRIBUTE_VALUE"] = attribute.Value;   

        return row;         
}

所以我又提出了三种方法:

LoopDeLoop->这是为了从主要方法中取出大部分循环,从而使循环更清晰。而且,它使sheets循环更清晰。

“ GetNewRows”->这是一个常见的IHarmonyAttribute循环,它摆脱了使用四个循环的需要。

GetNewRow->这只是填充了新的一行,但是现在您不必重复四遍。

希望这会有所帮助