I’m in trouble with some of my code,
I want to call a method but the method does not get called and I do not know why.
var rows = GetDataGridRows(dgTickets);
int intTickets = 0;
foreach (System.Windows.Controls.DataGridRow r in rows)
{
//some code
}
private IEnumerable<System.Windows.Controls.DataGridRow>
GetDataGridRows(System.Windows.Controls.DataGrid grid)
{
var itemsSource = grid.ItemsSource as IEnumerable;
if (null == itemsSource) yield return null;
foreach (var item in itemsSource)
{
var row = grid.ItemContainerGenerator.ContainerFromItem(item)
as System.Windows.Controls.DataGridRow;
if (null != row) yield return row;
}
}
var rows = GetDataGridRows(dgTickets); doesn’t call the function and just go to int intTickets = 0
I have no idea what to do
Thanks in advance
Your method
GetDataGridRowsreturns anIEnumerableusingyield. It’s not until yourforeachblock is executed that you’ll step into this method.The use of the
yieldkeyword allows the C# compiler to use it’s state machine generator to create an implementation ofIEnumerablewhich it returns.IEnumerableuse lazy invocation, which essentially means it’s only interated when it is required. This is where you see it jumping over the declaration to the next step, because at that point, it is only an instance ofIEnuemrablewhich has yet to be cycled through.