Let's take a quick look at a new feature in CodeSmith called IndexedEnumerable. IndexedEnumerable provides a smarter way to iterate collections. The best way to see this is with a quick sample. We will get a list of tables and iterate the collection as an indexedenumerable.
<% IndexedEnumerable<TableSchema> tables = SourceDatabase.Tables .Where(t => t.HasPrimaryKey && t.PrimaryKey.MemberColumns.Count == 1) .AsIndexedEnumerable(); foreach (var item in tables) { %> ----------------------------------- Table Name is <%=item.Value.Name %> // Value is the current item in the collection Index is <%=item.Index %> // Index is the current index IsFirst is <%=item.IsFirst %> // IsFirst lets you know if the current item is the first item in the collection IsLast is <%=item.IsLast %> // IsLast lets you know if the current item is the last item in the collection IsEven is <%=item.IsEven %> // IsEven lets you know if the current item is an even numbered index in the collection IsOdd is <%=item.IsOdd %> // IsOdd lets you know if the current item is an odd numbered index in the collection ----------------------------------- <%}%>
A template is attached containing the code you see here. Run the template against the Petshop Database located in the CodeSmith samples folder, you can see IndexedEnumerable at work.
When you need to know where you are while iterating a collection, Turn your collection into an IndexedEnumerable and it will make life much easier when making decisions based on the index of the current item in the collection.
Personal Licenses Available Now CodeSmith is now offering personal licenses for individual developers