static
List<
int
> GetInitialData()
ide
{
return
new
List<
int
>(){1,2,3,4};
}
static
IEnumerable<
int
> FilterWithoutYield()
{
List<
int
> result =
new
List<
int
>();
foreach
(
int
i
in
GetInitialData())
{
if
(i > 2)
{
result.Add(i);
}
}
return
result;
}
static
IEnumerable<
int
> FilterWithYield()
{
foreach
(
int
i
in
GetInitialData())
{
if
(i > 2)
{
yield
return
i;
}
}
yield
break
;
Console.WriteLine(
"這裏的代碼不執行"
);
}
總結:this
經過單步調試發現:spa
雖然2種方法的輸出結果是同樣的,但運做過程迥然不一樣。第一種方法,是把結果集所有加載到內存中再遍歷;第二種方法,客戶端每調用一次,yield return就返回一個值給客戶端,是"按需供給"。調試
第一種方法,客戶端調用過程大體爲:code
使用yield return,客戶端調用過程大體爲:blog
so,like this is cool:遞歸
/// <summary>
/// 遞歸構造商品分類
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
private IEnumerable<ProductCategory> RecursionCategory(IEnumerable<ProductCategoryExt> source)
{
if (source.IsHasRow())
{
foreach (var item in source)
{
yield return new ProductCategory()
{
ParentId = item.ParentId,
CateId = item.ProductCategoryId,
CateName = item.VchMobileShowName,
IcoUrl = item.CatePic,
};
}
}
}