通过迭代器为序列创建可组合的API

通常,对于一个集合的操作会封装多个逻辑

如果将这些逻辑全部写在一个循环里面,那么逻辑本身的可重用性就大打折扣。

如果讲每个逻辑都单独写个循环,那么程序的性能就会收到影响。

那么该如何做呢?幸好有延迟执行(deffered execution model)模型。代码如下。

 

class Program
{
static void Main()
{
int[] arrint = { 3, 5, 1, 3, 6, 4, 2, 1, 6 };
foreach (var item in Square(Unique(arrint)))
{
Console.WriteLine(
"arrint " + item);
}

MyControl[] arrcon
= { new MyControl(1, "aaa"), new MyControl(2, "bbb"), new MyControl(2, "bbb"), new MyControl(3, "ccc") };
foreach (var item in Square(Unique(arrcon)))
{
Console.WriteLine(
"arrcon " + item);
}

}
static IEnumerable<T> Unique<T>(IEnumerable<T> nums)
{
Dictionary
<string, T> uniqueVals = new Dictionary<string, T>();
foreach (T num in nums)
{
if (!uniqueVals.ContainsKey(num.ToString()))
{
uniqueVals.Add(num.ToString(), num);
yield return num;
}
}
}

static IEnumerable<Int32> Square<T>(IEnumerable<T> nums)
{
foreach (var item in nums)
{
yield return Int32.Parse(item.ToString()) * Int32.Parse(item.ToString());
}
}
}
class MyControl
{
public int MaxLength { get; set; }
public string Text { get; set; }
public MyControl(int l, string t)
{
this.MaxLength = l;
this.Text = t;
}
public int GetLength()
{
return this.MaxLength;
}
public override string ToString()
{
return this.MaxLength.ToString();
}
}

 

 

 

posted @ 2011-01-02 13:38  cnbwang  阅读(202)  评论(0编辑  收藏  举报