0

I am using this syntax in my foreach loop and it loops through as it should, but is there a way to have the loop start at the last index instead of the first?

This is the syntax I am using to start at the first element, but could it be altered so that it starts reverse?

foreach (BD bData in bl.NameList)
{
Object[] param = new Object[2];
param[0] = bData.m_Width;
param[1] = bData.m_Height;
DataGrid1.Rows.Insert(0, param);
}
IcyPopTarts
  • 494
  • 1
  • 12
  • 25

2 Answers2

2

I am not sure what data type BD is, but I have to assume it is an indexable list (i.e. it has a this[int] property, and either a Count, GetUpperBound(), or Length property). Otherwise the question "can I do it in reverse order?" is a meaningless question, because you would be working with a list with indeterminate order which would also have an indeterminate reverse order.

So, given that it is indexable, you simply need to use a for loop instead of foreach.

for (int i = bd.NameList.Count-1; i>=0; i--)
{
    var bData = bd.NameList[i];
    Object[] param = new Object[2];
    param[0] = bData.m_Width;
    param[1] = bData.m_Height;
    DataGrid1.Rows.Insert(0, param);
}

Or... if you love the enumerator... just use Add(X) instead of Insert(0, X), which will append to the end of the list. Obviously this will only work if you are adding to a DataGridViewRowCollection and may not work in other situations.

foreach (BD bData in bl.NameList)
{
    Object[] param = new Object[2];
    param[0] = bData.m_Width;
    param[1] = bData.m_Height;
    DataGrid1.Rows.Add(param);
}
John Wu
  • 50,556
  • 8
  • 44
  • 80
1

You could use reverse the list before putting it through foreach, but that is not as efficient as simply using a for loop and iterating through it backwards, as described here: Possible to iterate backwards through a foreach?

Felix Guo
  • 2,700
  • 14
  • 20