Unable to step into or break in method called inside Linq query/expression

故事扮演 提交于 2020-01-13 19:20:49

问题


I have encountered a bizarre issue trying to step into a method called from within a Linq query (although I also experience the problem when using a Linq expression). The code compiles, AND it appears to work (I get the outcome I was expecting).

IEnumerable<TagBuilder> theOutcome = from r in resultSet
                                     select GetTableDataRow(null);

OR

IEnumerable<TagBuilder> theOutcome = resultSet.Select(r => GetTableDataRow(null));

The method being called is defined as follows:

private static TagBuilder GetTableDataRow(IEnumerable<object> rowData)
{
    TagBuilder tr = new TagBuilder("tr");
    return tr;
}

The resultSet variable is an IPagedList that contains two items.

The variable theOutcome ends up holding two TagBuilder instances as expected.

However, I cannot then step into GetTableDataRow(), even if I put a breakpoint on or before the Linq query in question. If I put a breakpoint IN the GetTableDataRow() method, it never hits that either.

I'm completely stumped. Can anyone help? Code is obviously very simple right now, but I'll NEED to step through the contents of that method with the debugger as I develop it.


回答1:


You need to evaluate the expression.

Just call ToArray(), ToList(), Count(), or any other method or extension on IEnumerable<T> which forces evaluation.

The result of Select is evaluated using deferred execution, so nothing happens with GetTableDataRow until the query is used.


More explicitly, you can see this by expanding out what Select does:

IEnumerable<TagBuilder> theOutcome = resultSet.Select(r => GetTableDataRow(null));

is equivalent to

IEnumerable<TagBuilder> theOutcome = getRows(resultSet);

where getRows is:

IEnumerable<TagBuilder> getRows(IEnumerable<IPagedList> source)
{
    foreach ( IPagedListitem in source )
        yield return GetTableDataRow(null);
}

Because GetTableDataRow is yield returned, it's not evaluated until the evaluation is forced (e.g. by ToArray(), etc.).



来源:https://stackoverflow.com/questions/29556223/unable-to-step-into-or-break-in-method-called-inside-linq-query-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!