Just create the material once, and pass it to the CreateCSforWall function. You can make it cleaner by filtering the selection ang get unique WallTypes from walls.
var selectedElementIds = uidoc.Selection.GetElementIds();
if (selectedElementIds != null)
{
using (Transaction t = new Transaction(doc, "Editing wall types"))
{
t.Start();
List<WallType> wallTypes = new List<WallType>();
Material concrete = CreateSampleConcreteMaterial();
foreach (ElementId id in selectedElementIds)
{
Element e = doc.GetElement(id);
if (e is Wall)
{
Wall w = e as Wall;
if (!wallTypes.Contains(w.WallType))
wallTypes.Add(w.WallType);
}
}
foreach(WallType wt in wallTypes)
{
CreateCSforWall(wt, concrete);
}
t.Commit();
t.Dispose();
}
}
Updated CreateCSforWall function:
public void CreateCSforWall(WallType wallType, Material concrete)
{
//wallType.Name = wallType.Name + "_WithNewCompoundStructure";
CompoundStructure wallCS = wallType.GetCompoundStructure();
// Create CompoundStructureLayers and add the materials created above to them.
List<CompoundStructureLayer> csLayers = new List<CompoundStructureLayer>();
CompoundStructureLayer structureLayer = new CompoundStructureLayer(0.5, MaterialFunctionAssignment.Structure, concrete.Id);
csLayers.Add(structureLayer);
// // Set the created layers to CompoundStructureLayer
wallCS.SetLayers(csLayers);
//Set which layer is used for structural analysis
wallCS.StructuralMaterialIndex = 0;
wallCS.SetNumberOfShellLayers(ShellLayerType.Exterior, 0);
wallCS.SetNumberOfShellLayers(ShellLayerType.Interior, 0);
// Set the new wall CompoundStructure to the type of wall.
wallType.SetCompoundStructure(wallCS);
}
Hitting Accepted Answer is a Community Contribution from me as well as from you.
======================================================================