Site:
Http://www.jb51.net/article/54810.htm
static
List<
int
> GetInitialData()
{
return
new
List<
int
>(){1,2,3,4};
}Print out all elements with values greater than 2
implementations that do not use yield return
static
IEnumerable<
int
> FilterWithoutYield()
{
List<
int
> result =
new
List<
int
>();
foreach
(
int
i
in
GetInitialData())
{
if
(i > 2)
{
result.Add(i);
}
}
return
result;
}
use yeild return to implement
static
IEnumerable<
int
> FilterWithYield()
{
foreach
(
int
i
in
GetInitialData())
{
if
(i > 2)
{
yield
return
i;
}
}
yield
break
;
Console.WriteLine(
"这里的代码不执行"
);
}
Summarize:
Discover with one-step debugging:
Although the output of the 2 methods is the same, the operating process is very different. The first method is to load the result set into memory and then traverse it, and the second method, each time the client calls, yields return a value to the client, which is "supply on demand".
The first method, the client invocation process is roughly:
With yield return, the client invocation process is roughly:
So,like This is cool:
/// <summary> ///recursive construction of commodity classification/// </summary> /// <param name= "source" ></param> /// <returns></returns> PrivateIenumerable<productcategory> Recursioncategory (ienumerable<productcategoryext>source) { if(source. Ishasrow ()) {foreach(varIteminchsource) { yield return NewProductCategory () {ParentID=item. ParentID, Cateid=item. ProductCategoryID, Catename=item. Vchmobileshowname, Icourl=item. Catepic,}; } } }View Code
Analysis of yield return usage in _c# of wheel building