I have below condition in my C# 2.0.
There is some VbScript code:
For i = 0 to UBound(components) - 1
If i = UBound(Components) - 1 Then
WriteOut "<div class=""clearBoth""></div>"
End If
Next
Below I am trying to write in C#, please suggest what condition will be written for “If i = UBound(Components) – 1 Then” in c#.
List<tc.ComponentPresentation> cmp = new List<tc.ComponentPresentation>();
foreach (tc.ComponentPresentation cm in cmp)
{
//Here I want to right one condition that
if(this is the last object in "cmp" list)
{
////do something
}
}
Please suggest!!
The simplest approach would be to use the indexer instead:
An alternative is to use something like the “smart enumerations” from MiscUtil, which lets you use a
foreachloop but still access the “is first”, “is last”, and “index” for each entry. With C# 3 it’s actually somewhat simpler to use than the code in that blog post:(As an aside,
tcis an odd namespace name…)EDIT: Note that checking whether your current item is equal to the last item in the list is not a reliable indication that you’re currently on the last iteration. It will only work if the list contains distinct elements. Both of the approaches above really tell you whether you’re on the last iteration, which is what I assumed you wanted.