Beginner’s Guide: Dictionary with the Revit API

A dictionary is a searchable object which uses a unique key and value pairing.  This video helps a beginner to create a dictionary with a key “integer" and “string" value.  Also how to create a dictionary with an “integer" key and "list of string" values.  I populate the dictionary using items from a Revit project using the element id as my keys and parameters/family name as values. 
I cover a simple lambda expression to search the key using a value.  I also use Linq to search for a value using the key.


Sample code:

          public Result Execute(
          ExternalCommandData commandData,
          ref string message,
          ElementSet elements)
        {
            // Revit application documents. 
            UIApplication uiapp = commandData.Application;
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Application app = uiapp.Application;
            Document doc = uidoc.Document;
            Dictionary<int, string> dictionary = new Dictionary<int, string>();
            List<Wall> ListWalls = getWalls(doc);
            foreach (Wall w in ListWalls)
            {
                dictionary.Add(w.Id.IntegerValue, w.Name);
            }
            int key = 928306;
            if (dictionary.ContainsKey(key))
            {
                string value = dictionary[key];
                TaskDialog.Show("value", "Value found by Key: " + value);
            }
            int elemIdKey = dictionary.FirstOrDefault(x => x.Value == "SW24").Key;
            TaskDialog.Show("ElementId", "Key found by Value: " + elemIdKey);

            //List of in dictionary
            Dictionary<int, List<string>> dictionaryList = new Dictionary<int, List<string>>();
            foreach(Wall w in ListWalls)
            {
                List<string> wallValues = new List<string>();
                string Base = w.LookupParameter("Base Constraint").AsValueString();
                string Top = w.LookupParameter("Top Constraint").AsValueString();
                wallValues.Add(w.Name);
                wallValues.Add(Base);
                wallValues.Add(Top);
                dictionaryList.Add(w.Id.IntegerValue, wallValues);
            }
            StringBuilder sb = new StringBuilder();
            foreach (int i in dictionaryList.Keys)
            {
                if (i.Equals(key))
                {
                    foreach (string s in dictionaryList[i])
                    {
                        sb.Append(s + "\n");
                    }
                }
            }
            TaskDialog.Show("value", "Dictionary List \n" + sb.ToString());
            return Result.Succeeded;
        }

Tips:
- Include the using statement for Linq.  

-Watch the previous video to find the get all wall method.

Comments

Popular Posts