应用程序:Loads

Revit平台:结构

Revit版本:2011.0

首次发布:9.0

编程语言:C#

技能等级:中等

类别:结构

类型:ExternalCommand

主题:操作荷载工况、荷载性质、荷载用途和荷载组合。

概要:

此示例展示了如何操作荷载工况、荷载性质、荷载用途和荷载组合。

类:

Autodesk.Revit.UI.IExternalCommand

Autodesk.Revit.DB.Structure.LoadCase

Autodesk.Revit.DB.Structure.LoadNature

Autodesk.Revit.DB.Structure.LoadCombination

Autodesk.Revit.Creation.Document

项目文件:

Loads.cs

这个文件中有一个名为Loads的类,它实现了IExternalCommand接口。这个文件使用其他文件来展示如何操作荷载工况、荷载性质、荷载用途和荷载组合。

 

LoadCaseDeal.cs

该文件包含操作负荷工况和负荷性质的函数。

 

LoadCombinationDeal.cs

该文件包含操作负荷组合和负荷用途的函数。

 

LoadCaseTabPage.cs

这个用户控件用于处理表单上的荷载工况操作。

 

LoadCombinationTabPage

这个用户控件用于处理表单上的荷载组合操作。

描述:

功能:

- 获取Revit项目中的所有荷载情况、荷载性质、荷载组合、荷载用途和公式。

- 展示当前项目中所有现有的负荷情况,包括它们的名称、情况编号、性质和类别;修改名称、性质和类别。然后允许用户将“复制”一个新的负荷情况到当前项目中,同时在对话框上显示它们。

- 显示所有负载自然属性(包括当前项目中已有的自然属性和添加的自然属性),名称可修改,并且一个“添加”按钮可用于添加新的自然属性。

- 将新的负载组合添加到当前项目中,并在创建时设置其参数,例如负荷情况和负荷用途。

- 删除特定的负载组合或负载用途。

实现:

- 可使用 Autodesk.Revit.Creation.Document 命名空间中的 NewLoadCase () NewLoadCombination () 方法创建新的负载情况和新的负载组合。

- 可使用 Autodesk.Revit.Creation.Document 命名空间中的 NewLoadNature () NewLoadUsage () 方法创建新的负载自然属性和负载用途。

- 可以使用名为“Load Case”的参数从 Load Instance 对象中检索负载情况元素。

- 可以通过迭代文档元素找到所有的负载自然属性、负载情况、负载组合和负载用途。

- 所有对象都有一个名称属性,可用于检索用户可见名称。

说明:

1. 运行命令,它将显示Revit项目中的所有荷载情况、荷载性质、荷载组合、荷载用途和公式。使用Revit菜单命令“设置->结构设置”可以打开类似的对话框。

2. 选择一个负荷情况,然后在“负荷情况”选项卡页中复制一个新的负荷情况。

3. 选择一个负荷自然属性,然后在“负荷情况”选项卡页中添加一个新的负荷自然属性。

4. 您可以在“负荷组合”选项卡页中使用“添加”或“删除”按钮创建新的负载组合或删除现有的负载组合。您还可以添加或删除负载组合用途。

源代码

完整的源代码请加入QQ群649037449,在群文件中下载RevitSDK.exe,解压后在文件夹中搜索本文中应用程序名称即可获得完整源码

Loads.cs

//
// (C) Copyright 2003-2019 by Autodesk, Inc. 
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable. 
//


using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

using Autodesk;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB.Structure;

namespace Revit.SDK.Samples.Loads.CS
{
    /// <summary>
    /// Implements the Revit add-in interface IExternalCommand
    /// </summary>
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
    [Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)]
    public class Loads : IExternalCommand
    {
        #region Private Data Members
        // Mainly used data definition
        Autodesk.Revit.ApplicationServices.Application m_revit;     // Store the reference of revit
        LoadCombinationDeal m_combinationDeal;  // the deal class on load combination page
        LoadCaseDeal m_loadCaseDeal;            // the deal class on load case page
        String m_errorInformation;              // Store the error information

        // Define the data mainly used in LoadCombinationDeal class
        List<String> m_usageNameList;       // Store all the usage names in current document
        List<LoadUsage> m_loadUsageList;    // Used to store all the load usages
        List<String> m_combinationNameList; // Store all the combination names in current document 
        List<LoadCombinationMap> m_LoadCombinationMap;
                                // Store all the Load Combination information include the user add.
        List<FormulaMap> m_formulaMap;      // Store the formula information the user add
        List<UsageMap> m_usageMap;

        // Define the data mainly used in LoadCaseDeal class             
        List<Category> m_loadCasesCategory;     //Store the load case's category
        List<LoadCase> m_loadCases;             //Store all the load cases in current document
        List<LoadNature> m_loadNatures;         //Store all the load natures in current document
        List<LoadCasesMap> m_loadCasesMap;      // Store all the load case information include the user add.
        List<LoadNaturesMap> m_loadNaturesMap;  //Store all the load natures information
        #endregion
        
        #region Properties
        /// <summary>
        /// Used as the dataSource of load cases DataGridView control,
        /// and the information which support load case creation also.
        /// </summary>
        public List<LoadCasesMap> LoadCasesMap
        {
            get
            {
                return m_loadCasesMap;
            }
        }

        /// <summary>
        /// Used as the dataSource of load natures DataGridView control,
        /// and the information which support load nature creation also.
        /// </summary>
        public List<LoadNaturesMap> LoadNaturesMap
        {
            get
            {
                return m_loadNaturesMap;
            }
        }

        /// <summary>
        /// save all loadnature object in current project
        /// </summary>
        public List<LoadNature> LoadNatures
        {
            get
            {
                return m_loadNatures;
            }
        }

        /// <summary>
        /// save all loadcase object in current project
        /// </summary>
        public List<LoadCase> LoadCases
        {
            get
            {
                return m_loadCases;
            }
        }

        /// <summary>
        /// save all load cases category in current project
        /// </summary>
        public List<Category> LoadCaseCategories
        {
            get
            {
                return m_loadCasesCategory;
            }
        }

        /// <summary>
        /// object which do add, delete and update command on load related objects
        /// </summary>
        public LoadCaseDeal LoadCasesDeal
        {
            get
            {
                return m_loadCaseDeal;
            }
        }

        /// <summary>
        /// Store the reference of revit
        /// </summary>
        public Autodesk.Revit.ApplicationServices.Application RevitApplication
        {
            get
            {
                return m_revit;
            }
        }

        /// <summary>
        /// LoadUsageNames property, used to store all the usage names in current document
        /// </summary>
        public List<String> LoadUsageNames
        {
            get
            {
                return m_usageNameList;
            }
        }

        /// <summary>
        /// Used to store all the load usages in current document, include the user add
        /// </summary>
        public List<LoadUsage> LoadUsages
        {
            get
            {
                return m_loadUsageList;
            }
        }

        /// <summary>
        /// LoadCombinationNames property, used to store all the combination names in current document
        /// </summary>
        public List<String> LoadCombinationNames
        {
            get
            {
                return m_combinationNameList;
            }
        }

        /// <summary>
        /// Show the error information while contact with revit
        /// </summary>
        public String ErrorInformation
        {
            get
            {
                return m_errorInformation;
            }
            set
            {
                m_errorInformation = value;
            }
        }

        /// <summary>
        /// Used as the dataSource of load combination DataGridView control,
        /// and the information which support load combination creation also.
        /// </summary>
        public List<LoadCombinationMap> LoadCombinationMap
        {
            get
            {
                return m_LoadCombinationMap;
            }
        }

        /// <summary>
        /// Store all load combination formula names
        /// </summary>
        public List<FormulaMap> FormulaMap
        {
            get
            {
                return m_formulaMap;
            }
        }

        /// <summary>
        /// Store all load usage
        /// </summary>
        public List<UsageMap> UsageMap
        {
            get
            {
                return m_usageMap;
            }
        }
        #endregion

        #region Methods
        /// <summary>
        /// Default constructor of Loads
        /// </summary>
        public Loads()
        {
            m_usageNameList = new List<string>();
            m_combinationNameList = new List<string>();
            m_LoadCombinationMap = new List<LoadCombinationMap>();
            m_loadUsageList = new List<LoadUsage>();
            m_formulaMap = new List<FormulaMap>();
            m_usageMap = new List<UsageMap>();

            m_loadCasesCategory = new List<Category>();
            m_loadCases = new List<LoadCase>();
            m_loadNatures = new List<LoadNature>();
            m_loadCasesMap = new List<LoadCasesMap>();
            m_loadNaturesMap = new List<LoadNaturesMap>();
        }

        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application 
        /// which contains data related to the command, 
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application 
        /// which will be displayed if a failure or cancellation is returned by 
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application 
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command. 
        /// A result of Succeeded means that the API external method functioned as expected. 
        /// Cancelled can be used to signify that the user cancelled the external operation 
        /// at some point. Failure should be returned if the application is unable to proceed with 
        /// the operation.</returns>
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData,
                                                    ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            m_revit = commandData.Application.Application;
            Transaction documentTransaction = new Transaction(commandData.Application.ActiveUIDocument.Document, "Document");
            documentTransaction.Start();
            // Initialize the helper classes.
            m_combinationDeal = new LoadCombinationDeal(this);
            m_loadCaseDeal = new LoadCaseDeal(this);

            // Prepare some data for the form displaying
            PrepareData();


            // Display the form and wait for the user's operate.
            // This class give some public methods to add or delete LoadUsage and delete LoadCombination
            // The form will use these methods to add or delete dynamically.
            // If the user press cancel button, return Cancelled to roll back All the changes.
            using (LoadsForm displayForm = new LoadsForm(this))
            {
                if (DialogResult.OK != displayForm.ShowDialog())
                {
                    documentTransaction.RollBack();
                    return Autodesk.Revit.UI.Result.Cancelled;
                }
            }

            // If everything goes right, return succeeded.
            documentTransaction.Commit();
            return Autodesk.Revit.UI.Result.Succeeded;
        }

        /// <summary>
        /// Prepare the data for the form displaying.
        /// </summary>
        void PrepareData()
        {
            // Prepare the data of the LoadCase page on form
            m_loadCaseDeal.PrepareData();

            //Prepare the data of the LoadCombination page on form
            m_combinationDeal.PrepareData();
        }

        /// <summary>
        /// Create new Load Combination
        /// </summary>
        /// <param name="name">The new Load Combination name</param>
        /// <param name="typeId">The index of new Load Combination Type</param>
        /// <param name="stateId">The index of new Load Combination State</param>
        /// <returns>true if the creation was successful; otherwise, false</returns>
        public Boolean NewLoadCombination(String name, int typeId, int stateId)
        {
            // In order to refresh the combination DataGridView,
            // We should do like as follow
            m_LoadCombinationMap = new List<LoadCombinationMap>(m_LoadCombinationMap);

            // Just go to run NewLoadCombination method of LoadCombinationDeal class
            return m_combinationDeal.NewLoadCombination(name, typeId, stateId);
        }

        /// <summary>
        /// Delete the selected Load Combination
        /// </summary>
        /// <param name="index">The selected index in the DataGridView</param>
        /// <returns>true if the delete operation was successful; otherwise, false</returns>
        public Boolean DeleteCombination(int index)
        {
            // Just go to run DeleteCombination method of LoadCombinationDeal class
            return m_combinationDeal.DeleteCombination(index);
        }

        /// <summary>
        /// Create a new load combination usage
        /// </summary>
        /// <param name="usageName">The new Load Usage name</param>
        /// <returns>true if the process is successful; otherwise, false</returns> 
        public Boolean NewLoadUsage(String usageName)
        {
            // In order to refresh the usage DataGridView,
            // We should do like as follow
            m_usageMap = new List<UsageMap>(m_usageMap);

            // Just go to run NewLoadUsage method of LoadCombinationDeal class
            return m_combinationDeal.NewLoadUsage(usageName);
        }

        /// <summary>
        /// Delete the selected Load Usage
        /// </summary>
        /// <param name="index">The selected index in the DataGridView</param>
        /// <returns>true if the delete operation was successful; otherwise, false</returns>
        public Boolean DeleteUsage(int index)
        {
            // Just go to run DeleteUsage method of LoadCombinationDeal class
            if (false == m_combinationDeal.DeleteUsage(index))
            {
                return false;
            }

            // In order to refresh the usage DataGridView,
            // We should do like as follow
            if (0 == m_usageMap.Count)
            {
                m_usageMap = new List<UsageMap>();
            }
            return true;
        }

        /// <summary>
        /// Change usage name when the user modify it on the form
        /// </summary>
        /// <param name="oldName">The name before modification</param>
        /// <param name="newName">The name after modification</param>
        /// <returns>true if the modification was successful; otherwise, false</returns>
        public Boolean ModifyUsageName(String oldName, String newName)
        {
            // Just go to run ModifyUsageName method of LoadCombinationDeal class
            return m_combinationDeal.ModifyUsageName(oldName, newName);
        }

        /// <summary>
        /// Add a formula when the user click Add button to new a formula
        /// </summary>
        /// <returns>true if the creation is successful; otherwise, false</returns>
        public Boolean AddFormula()
        {
            // Get the first member in LoadCases as the Case
            LoadCase loadCase = m_loadCases[0];
            if (null == loadCase)
            {
                m_errorInformation = "Can't not find a LoadCase.";
                return false;
            }
            String caseName = loadCase.Name;

            // In order to refresh the formula DataGridView,
            // We should do like as follow
            m_formulaMap = new List<FormulaMap>(m_formulaMap);

            // Run AddFormula method of LoadCombinationDeal class
            return m_combinationDeal.AddFormula(caseName);
        }

        /// <summary>
        /// Delete the selected Load Formula
        /// </summary>
        /// <param name="index">The selected index in the DataGridView</param>
        /// <returns>true if the delete operation was successful; otherwise, false</returns>
        public Boolean DeleteFormula(int index)
        {
            // Just remove that data.
            try
            {
                m_formulaMap.RemoveAt(index);
            }
            catch (Exception e)
            {
                m_errorInformation = e.ToString();
                return false;
            }
            return true;
        }
        #endregion
    }
}

LoadCaseDeal.cs

//
// (C) Copyright 2003-2019 by Autodesk, Inc. 
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable. 
//


using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

using Autodesk;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB.Structure;

namespace Revit.SDK.Samples.Loads.CS
{
    /// <summary>
    /// Deal the LoadCase class which give methods to connect Revit and the user operation on the form
    /// </summary>
    public class LoadCaseDeal
    {
        // Private Members
        Autodesk.Revit.ApplicationServices.Application m_revit; // Store the reference of revit application
        Loads m_dataBuffer;                 
        List<string> m_newLoadNaturesName; //store all the new nature's name that should be added

        // Methods
        /// <summary>
        /// Default constructor of LoadCaseDeal
        /// </summary>
        public LoadCaseDeal(Loads dataBuffer)
        {
            m_dataBuffer = dataBuffer;
            m_revit = dataBuffer.RevitApplication;
            m_newLoadNaturesName = new List<string>();

            m_newLoadNaturesName.Add("EQ1");
            m_newLoadNaturesName.Add("EQ2");
            m_newLoadNaturesName.Add("W1");
            m_newLoadNaturesName.Add("W2");
            m_newLoadNaturesName.Add("W3");
            m_newLoadNaturesName.Add("W4");
            m_newLoadNaturesName.Add("Other");
        }

        /// <summary>
        /// prepare data for the dialog
        /// </summary>
        public void PrepareData()
        {
            //Create seven Load Natures first
            CreateLoadNatures();

            //get all the categories of load cases
            UIApplication uiapplication = new UIApplication(m_revit);
            Categories categories = uiapplication.ActiveUIDocument.Document.Settings.Categories;
            Category category = categories.get_Item(BuiltInCategory.OST_LoadCases);
            CategoryNameMap categoryNameMap = category.SubCategories;
            System.Collections.IEnumerator iter = categoryNameMap.GetEnumerator();
            iter.Reset();
            while (iter.MoveNext())
            {
                Category temp = iter.Current as Category;
                if (null == temp)
                    continue;

                m_dataBuffer.LoadCaseCategories.Add(temp);
            }

            //get all the loadnatures name
            IList<Element> elements = new FilteredElementCollector(uiapplication.ActiveUIDocument.Document).OfClass(typeof(LoadNature)).ToElements();
            foreach (Element e in elements)
            {
                LoadNature nature = e as LoadNature;
                if (null != nature)
                {
                    m_dataBuffer.LoadNatures.Add(nature);
                    LoadNaturesMap newLoadNaturesMap = new LoadNaturesMap(nature);
                    m_dataBuffer.LoadNaturesMap.Add(newLoadNaturesMap);

                }
            }
            elements = new FilteredElementCollector(uiapplication.ActiveUIDocument.Document).OfClass(typeof(LoadCase)).ToElements();
            foreach (Element e in elements)
            {
                //get all the loadcases
                LoadCase loadCase = e as LoadCase;
                if (null != loadCase)
                {
                    m_dataBuffer.LoadCases.Add(loadCase);
                    LoadCasesMap newLoadCaseMap = new LoadCasesMap(loadCase);
                    m_dataBuffer.LoadCasesMap.Add(newLoadCaseMap);
                }
            }
        }

        /// <summary>
        /// create some load case natures named EQ1, EQ2, W1, W2, W3, W4, Other
        /// </summary>
        /// <returns></returns>
        private bool CreateLoadNatures()
        {
            //try to add some new load natures
            try
            {
                UIApplication uiapplication = new UIApplication(m_revit);
                foreach (string name in m_newLoadNaturesName)
                {
                    LoadNature.Create(uiapplication.ActiveUIDocument.Document, name);
                }

            }
            catch (Exception e)
            {
                m_dataBuffer.ErrorInformation += e.ToString();
                return false;
            }
            return true;
        }

        /// <summary>
        /// add a new load nature
        /// </summary>
        /// <param name="index">the selected nature's index in the nature map</param>
        /// <returns></returns>
        public bool AddLoadNature(int index)
        {

            string natureName = null;  //the load nature's name to be added
            bool isUnique = false;     // check if the name is unique    
            LoadNaturesMap myLoadNature = null;

            //try to get out the loadnature from the map
            try
            {
                myLoadNature = m_dataBuffer.LoadNaturesMap[index];
            }
            catch (Exception e)
            {
                m_dataBuffer.ErrorInformation += e.ToString();
                return false;
            }

            //Can not get the load nature
            if (null == myLoadNature)
            {
                m_dataBuffer.ErrorInformation += "Can't find the nature";
                return false;
            }

            //check if the name is unique
            natureName = myLoadNature.LoadNaturesName;
            while (!isUnique)
            {
                natureName += "(1)";
                isUnique = IsNatureNameUnique(natureName);
            }

            //try to create a load nature
            try
            {
                UIApplication uiapplication = new UIApplication(m_revit);
                LoadNature newLoadNature = LoadNature.Create(uiapplication.ActiveUIDocument.Document, natureName);
                if (null == newLoadNature)
                {
                    m_dataBuffer.ErrorInformation += "Create Failed";
                    return false;
                }

                //add the load nature into the list and maps
                m_dataBuffer.LoadNatures.Add(newLoadNature);
                LoadNaturesMap newMap = new LoadNaturesMap(newLoadNature);
                m_dataBuffer.LoadNaturesMap.Add(newMap);
            }
            catch (Exception e)
            {
                m_dataBuffer.ErrorInformation += e.ToString();
                return false;
            }
            return true;
        }
      
        /// <summary>
        /// Duplicate a new load case
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public bool DuplicateLoadCase(int index)
        {
            LoadCasesMap myLoadCase = null;
            bool isUnique = false;
            string caseName = null;

            //try to get the load case from the map
            try
            {
                myLoadCase = m_dataBuffer.LoadCasesMap[index];
            }
            catch (Exception e)
            {
                m_dataBuffer.ErrorInformation += e.ToString();
                return false;
            }

            //get nothing 
            if (null == myLoadCase)
            {
                m_dataBuffer.ErrorInformation += "Can not find the load case";
                return false;
            }

            //check the name
            caseName = myLoadCase.LoadCasesName;
            while (!isUnique)
            {
                caseName += "(1)";
                isUnique = IsCaseNameUnique(caseName);
            }

            //get the selected case's nature
            Autodesk.Revit.DB.ElementId categoryId = myLoadCase.LoadCasesSubCategoryId;
            Autodesk.Revit.DB.ElementId natureId = myLoadCase.LoadCasesNatureId;

            UIApplication uiapplication = new UIApplication(m_revit);

            //try to create a load case
            try
            {
                LoadCase newLoadCase = LoadCase.Create(uiapplication.ActiveUIDocument.Document, caseName, natureId, categoryId);
                if (null == newLoadCase)
                {
                    m_dataBuffer.ErrorInformation += "Create Load Case Failed";
                    return false;
                }
                //add the new case into list and map
                m_dataBuffer.LoadCases.Add(newLoadCase);
                LoadCasesMap newLoadCaseMap = new LoadCasesMap(newLoadCase);
                m_dataBuffer.LoadCasesMap.Add(newLoadCaseMap);
            }
            catch (Exception e)
            {
                m_dataBuffer.ErrorInformation += e.ToString();
                return false;
            }
            return true;
        }

        /// <summary>
        /// check if the case's name is unique
        /// </summary>
        /// <param name="name">the name to be checked</param>
        /// <returns>true will be returned if the name is unique</returns>
        public bool IsCaseNameUnique(string name)
        {
            //compare the name with the name of each case in the map
            for (int i = 0; i < m_dataBuffer.LoadCasesMap.Count; i++)
            {
                string nameTemp = m_dataBuffer.LoadCasesMap[i].LoadCasesName;
                if (name == nameTemp)
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// check if the nature's name is unique
        /// </summary>
        /// <param name="name">the name to be checked</param>
        /// <returns>true will be returned if the name is unique</returns>
        public bool IsNatureNameUnique(string name)
        {
            //compare the name with the name of each nature in the map
            for (int i = 0; i < m_dataBuffer.LoadNatures.Count; i++)
            {
                string nameTemp = m_dataBuffer.LoadNaturesMap[i].LoadNaturesName;
                if (name == nameTemp)
                {
                    return false;
                }
            }
            return true;
        }
    }
}

LoadCombinationDeal.cs

//
// (C) Copyright 2003-2019 by Autodesk, Inc. 
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable. 
//


using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

using Autodesk;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB.Structure;

namespace Revit.SDK.Samples.Loads.CS
{
    /// <summary>
    /// mainly deal class which give methods to connect Revit and the user operation on the form
    /// </summary>
    public class LoadCombinationDeal
    {
        // Private Members
        Loads m_dataBuffer;                 // Store the reference of Loads
        Autodesk.Revit.ApplicationServices.Application m_revit; // Store the reference of revit
        Autodesk.Revit.DB.Document m_document; // Store the reference of document

        // Methods
        /// <summary>
        /// Default constructor of LoadCombinationDeal
        /// </summary>
        public LoadCombinationDeal(Loads dataBuffer)
        {
            m_dataBuffer = dataBuffer;
            m_revit = dataBuffer.RevitApplication;
            UIApplication uiapplication = new UIApplication(m_revit);
            m_document = uiapplication.ActiveUIDocument.Document;
        }

        /// <summary>
        /// Find out all Load Combination and Usage in the existing document.
        /// As specification require, prepare some Load Combination Usages if they are not in document
        /// </summary>
        public void PrepareData()
        {
            // Find out all  Load Combination and Usage in the existing document.
            IList<Element> elements = (new FilteredElementCollector(m_document)).OfClass(typeof(LoadCombination)).ToElements();
            foreach (Element elem in elements)
            {
                LoadCombination combination = elem as LoadCombination;
                if (null != combination)
                {
                    // Add the Load Combination name.
                    m_dataBuffer.LoadCombinationNames.Add(combination.Name);

                    // Create LoadCombinationMap object.
                    LoadCombinationMap combinationMap = new LoadCombinationMap(combination);

                    // Add the LoadCombinationMap object to the array list.
                    m_dataBuffer.LoadCombinationMap.Add(combinationMap);
                }
            }

            elements = (new FilteredElementCollector(m_document)).OfClass(typeof(LoadUsage)).ToElements();
            foreach (Element elem in elements)
            {
                // Add Load Combination Usage information
                LoadUsage usage = elem as LoadUsage;
                if (null != usage)
                {
                    // Add the Load Usage name
                    m_dataBuffer.LoadUsageNames.Add(usage.Name);

                    // Add the Load Usage object to a LoadUsageArray
                    m_dataBuffer.LoadUsages.Add(usage);

                    // Add the Load Usage information to UsageMap.
                    UsageMap usageMap = new UsageMap(m_dataBuffer, usage.Name);
                    m_dataBuffer.UsageMap.Add(usageMap);
                }
            }

            // As specification require, some Load Combination Usages if they are not in document
            String[] initUsageArray = { "Gravity", "Lateral", "Steel", "Composite", "Concrete" };
            foreach (String s in initUsageArray)
            {
                NewLoadUsage(s);
            }
        }

        /// <summary>
        /// Create new Load Combination
        /// </summary>
        /// <param name="name">The new Load Combination name</param>
        /// <param name="typeIndex">The index of new Load Combination Type</param>
        /// <param name="stateIndex">The index of new Load Combination State</param>
        /// <returns>true if the creation was successful; otherwise, false</returns>
        public Boolean NewLoadCombination(String name, int typeIndex, int stateIndex)
        {
            // Define some data for creation.
            List<ElementId> usageIds = new List<ElementId>();
            List<LoadComponent> components = new List<LoadComponent>();
            double[] factorArray = new double[m_dataBuffer.FormulaMap.Count];

            // First check whether the name has been used
            foreach (String s in m_dataBuffer.LoadCombinationNames)
            {
                if (s == name || null == name)
                {
                    m_dataBuffer.ErrorInformation = "the combination name has been used.";
                    return false;
                }
            }

            // Get the usage information.
            foreach (UsageMap usageMap in m_dataBuffer.UsageMap)
            {
                if (true == usageMap.Set)
                {
                    LoadUsage usage = FindUsageByName(usageMap.Name);
                    if (null != usage)
                    {
                        usageIds.Add(usage.Id);
                    }
                }
            }

            // Get the formula information
            for (int i = 0; i < m_dataBuffer.FormulaMap.Count; i++)
            {
                FormulaMap formulaMap = m_dataBuffer.FormulaMap[i];
                factorArray[i] = formulaMap.Factor;
                LoadCase loadCase = FindLoadCaseByName(formulaMap.Case);
                if (null != loadCase)
                {
                    LoadComponent component = new LoadComponent(loadCase.Id, formulaMap.Factor);
                    components.Add(component);
                }
            }


            // Begin to new a load combination
            try
            {
                LoadCombination loadCombination = LoadCombination.Create(m_document, name, (LoadCombinationType)typeIndex, (LoadCombinationState)stateIndex);
                if (null == loadCombination)
                {
                    m_dataBuffer.ErrorInformation = "Get null reference after usage creation.";
                    return false;
                }
                loadCombination.SetComponents(components);
                loadCombination.SetUsageIds(usageIds);

                // Store this load combination information for further use
                m_dataBuffer.LoadCombinationNames.Add(loadCombination.Name);
                LoadCombinationMap combinationMap = new LoadCombinationMap(loadCombination);
                m_dataBuffer.LoadCombinationMap.Add(combinationMap);
            }
            catch (Exception e)
            {
                m_dataBuffer.ErrorInformation = e.Message;
                return false;
            }

            // If create combination successful, reset the usage check state and clear the formula
            foreach (UsageMap usageMap in m_dataBuffer.UsageMap)
            {
                usageMap.Set = false;
            }
            m_dataBuffer.FormulaMap.Clear();
            return true;
        }

        /// <summary>
        /// Delete the selected Load Combination
        /// </summary>
        /// <param name="index">The selected index in the DataGridView</param>
        /// <returns>true if the delete operation was successful; otherwise, false</returns>
        public Boolean DeleteCombination(int index)
        {
            // Get the name of the delete combination
            String combinationName = m_dataBuffer.LoadCombinationNames[index];

            // Find the combination by the name and delete the combination
            LoadCombination combination;
            IList<Element> elements = (new FilteredElementCollector(m_document)).OfClass(typeof(LoadCombination)).ToElements();
            foreach (Element elem in elements)
            {
                combination = elem as LoadCombination;

                if (combinationName == combination.Name)
                {
                    // Begin to delete the combination
                    try
                    {
                        m_document.Delete(combination.Id);
                    }
                    catch (Exception e)
                    {
                        m_dataBuffer.ErrorInformation = e.ToString();
                        return false;
                    }
                    break;
                }
            }

            // If delete is successful, Change the map and the string List
            m_dataBuffer.LoadCombinationMap.RemoveAt(index);
            m_dataBuffer.LoadCombinationNames.RemoveAt(index);

            return true;
        }

        /// <summary>
        /// Create a new load combination usage
        /// </summary>
        /// <param name="usageName">The new Load Usage name</param>
        /// <returns>true if the process is successful; otherwise, false</returns> 
        public Boolean NewLoadUsage(String usageName)
        {
            // First check whether the name has been used
            foreach (String s in m_dataBuffer.LoadUsageNames)
            {
                if (usageName == s)
                {
                    m_dataBuffer.ErrorInformation = "the usage name has been used.";
                    return false;
                }
            }

            // Begin to new a load combination usage
            try
            {
                LoadUsage loadUsage = LoadUsage.Create(m_document, usageName);
                if (null == loadUsage)
                {
                    m_dataBuffer.ErrorInformation = "Get null reference after usage creation.";
                    return false;
                }
                // Store this load usage information for further use.
                m_dataBuffer.LoadUsageNames.Add(loadUsage.Name);
                m_dataBuffer.LoadUsages.Add(loadUsage);

                // Add the Load Usage information to UsageMap.
                UsageMap usageMap = new UsageMap(m_dataBuffer, loadUsage.Name);
                m_dataBuffer.UsageMap.Add(usageMap);
            }
            catch (Exception e)
            {
                m_dataBuffer.ErrorInformation = e.Message;
                return false;
            }

            return true;
        }

        /// <summary>
        /// Delete the selected Load Usage
        /// </summary>
        /// <param name="index">The selected index in the DataGridView</param>
        /// <returns>true if the delete operation was successful; otherwise, false</returns>
        public Boolean DeleteUsage(int index)
        {
            // Get the delete usage
            LoadUsage deleteUsage = m_dataBuffer.LoadUsages[index];
            String usageName = deleteUsage.Name;

            // Begin to delete the combination
            try
            {
                m_document.Delete(deleteUsage.Id);
            }
            catch (Exception e)
            {
                m_dataBuffer.ErrorInformation = e.ToString();
                return false;
            }

            // Modify the data to show the delete operation
            m_dataBuffer.LoadUsages.RemoveAt(index);
            m_dataBuffer.LoadUsageNames.RemoveAt(index);
            m_dataBuffer.UsageMap.RemoveAt(index);

            // Need to delete corresponding in Combination
            foreach (LoadCombinationMap map in m_dataBuffer.LoadCombinationMap)
            {
                String oldUsage = map.Usage;
                int location = oldUsage.IndexOf(usageName);
                if (-1 == location)
                {
                    continue;
                }
                if (oldUsage.Length == usageName.Length)
                {
                    map.Usage = oldUsage.Remove(0);
                    continue;
                }
                if (0 == location)
                {
                    map.Usage = oldUsage.Remove(location, usageName.Length + 1);
                }
                else
                {
                    map.Usage = oldUsage.Remove(location - 1, usageName.Length + 1);
                }
            }

            return true;
        }

        /// <summary>
        /// Change usage name when the user modify it on the form
        /// </summary>
        /// <param name="oldName">The name before modification</param>
        /// <param name="newName">The name after modification</param>
        /// <returns>true if the modification was successful; otherwise, false</returns>
        public Boolean ModifyUsageName(String oldName, String newName)
        {
            // If the name is no change, just return true.
            if (oldName == newName)
            {
                return true;
            }

            // Check whether the name has been used
            foreach (String s in m_dataBuffer.LoadUsageNames)
            {
                if (s == newName)
                {
                    TaskDialog.Show("Revit", "There is a same named usage already.");
                    return false;
                }
            }

            // Begin to modify the name of the usage
            foreach (LoadUsage usage in m_dataBuffer.LoadUsages)
            {
                if (oldName == usage.Name)
                {
                    usage.get_Parameter(BuiltInParameter.LOAD_USAGE_NAME).Set(newName);
                }
            }
            return true;
        }

        /// <summary>
        /// Add a formula with the load case name
        /// </summary>
        /// <param name="caseName">The name of the load case</param>
        /// <returns>true if the creation is successful; otherwise, false</returns>
        public Boolean AddFormula(String caseName)
        {
            // New a FormulaMap, and add it to m_dataBuffer.FormulaMap
            // Note: the factor of the formula is always set 1 
            FormulaMap map = new FormulaMap(caseName);
            m_dataBuffer.FormulaMap.Add(map);
            return true;
        }

        /// <summary>
        /// Find a load usage by the load usage name
        /// </summary>
        /// <param name="name">The name of load usage</param>
        /// <returns>The reference of the LoadUsage</returns>
        private LoadUsage FindUsageByName(String name)
        {
            LoadUsage usage = null;
            foreach (LoadUsage l in m_dataBuffer.LoadUsages)
            {
                if (name == l.Name)
                {
                    usage = l;
                    break;
                }
            }
            return usage;
        }

        /// <summary>
        /// Find a load case by the load case name
        /// </summary>
        /// <param name="name">The name of load case</param>
        /// <returns>The reference of the LoadCase</returns>
        private LoadCase FindLoadCaseByName(String name)
        {
            LoadCase loadCase = null;
            foreach (LoadCase l in m_dataBuffer.LoadCases)
            {
                if (name == l.Name)
                {
                    loadCase = l;
                    break;
                }
            }
            return loadCase;
        }
    }
}