Get last element in a loop

316 Views Asked by At
for (int ixIdx = 0; ixIdx < tblAttributes.Count; ixIdx++)
      {
          bool Exclude = ExcludeColumn(tblAttributes[ixIdx].Name);
                  bool Primary = Primary(tblAttributes[ixIdx].Name);
                  if (Exclude || Primary)
          {
              continue;
          }
          else
          {
    #>    [<#= tblAttributes[ixIdx].MdlPart.InternalName #>]<#= ixIdx == tblAttributes.Count-1 ? "" : "," #>
    <#    }
        }

in the above code is in texttemplate file . what all i am trying to do is generate a comma for each element of list tblAttributes those comes in to else and stop comma at the last element of the list.....

The issue is as my condition is in else it is applying , but after that last elements are falling in to if block so it never stops the comma generation . so is there any possibility to find the last element that comes to else block....to get this done ...

or is there any work around for the whole process plz ....thanks........

2

There are 2 best solutions below

5
On

for your comma problem, you can do it like this for a general purpose:

string res = "";
for(int i = 0; i < list.Count - 1; i++)
    res += list[i] + ", ";
if (list.Count > 0) res += list[list.Count - 1];

in your particular case (since not every element is added to your string):

string res = "";
int i = 0;
while (i < tblAttributes.Count && (ExcludeColumn(tblAttributes[i].Name) || (Primary(tblAttributes[i].Name)))
    i++;

if (i < tblAttributes.Count) res += tblAttributes[i].Name;

for (; i < tblAttributes.Count; i++)
{
    if (!ExcludeColumn(tblAttributes[i].Name) && !(Primary(tblAttributes[i].Name))
        res += ", " + tblAttributes[i].Name;
}

that way you only add a comma if you have another element to add to your resulting string. If there is no elements that match your condition the string will be empty. If there is only one, your string won't have a comma at the end. If there is more than one element, you place the comma before adding a new element, so no risks that your string ends with a comma either.

0
On

the simple thing u could do is

iterate the list in for loop and push the elements that satisfies ur conditions into a new list and then iterate the new list so that u can use the simple logic below to stop generating the comma at the end of last element of the new list in the loop.

for(int i = 0; i < newlist.Count; i++)
{ 
   <#= newlist[i] #><#= i == newlist.Count - 1 ? "" : "," #>
}

that will do thanks..........