C#中yield return的用法示例
2021-03-24 03:24
标签:item int gen color 读取 code [] static rabl C#中yield return的用法示例 标签:item int gen color 读取 code [] static rabl 原文地址:https://www.cnblogs.com/xiaowangzhi/p/9446572.htmlusing System;
using System.Collections.Generic;
namespace YieldReturn
{
class Program
{
static void Main(string[] args)
{
var list = new Listint> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var resultNormal = EvenNormal(list);
foreach (var item in resultNormal)
{
Console.WriteLine(item);
}
var resultYieldReturn = EvenYieldReturn(list);
foreach (var item in resultYieldReturn)
{
Console.WriteLine(item);
}
}
static IEnumerableint> EvenNormal(Listint> list)
{
var result = new Listint>();
foreach (var item in list)
{
if (item % 2 == 0)
{
result.Add(item);// 类似DataSet(整个结果集加载到内存中),适合少量数据的遍历
}
}
return result;
}
static IEnumerableint> EvenYieldReturn(Listint> list)
{
foreach (var item in list)
{
if (item % 2 == 0)
{
yield return item;// 类似DataReader(读取一条返回一条),适合海量数据的遍历
}
}
yield break;
}
}
}
文章标题:C#中yield return的用法示例
文章链接:http://soscw.com/index.php/essay/67879.html