Javen-Studio 咖啡小屋

http://javenstudio.org - C++ Java 分布式 搜索引擎
Naven's Research Laboratory - Thinking of Life, Imagination of Future

  开发者Cpp博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  24 随笔 :: 57 文章 :: 170 评论 :: 4 Trackbacks

4.2         聚合操作符(Aggregation Operators)

有几个标准查询操作符(standard query operators)定义用来聚合(aggregating)一组值的序列(a sequence of values)成一个单独的值(a single value)。最普通的聚合操作符(most general aggregation operator)就是 Fold,它的定义看起来如下所示:

 

public static U Fold<T, U>(this IEnumerable<T> source, 
                           U seed, Func
<U, T, U> func) {
  U result 
= seed;

  
foreach (T element in source) 
      result 
= func(result, element);

  
return result;
}

 

Fold 操作符使它对一组值的序列(a sequence of values)简单地执行一个计算(perform a calculation)处理。Fold 工作的方式是对基本的序列(the underlying sequence)的每一个成员调用一次 lambda 表达式。每一次 Fold 调用 lambda 表达式的时候,它既从序列(sequence)传递(passes)成员(members)又传递一个聚合的值(aggregated value)(该初始化的值(initial value)对 Fold 是基于种子参数(seed parameter))。Lambda 表达式的结果替换了以前的聚合的值(the previous aggregated value),Fold 返回了 lambda 表达式的最终结果(the final result)。

 

例于,下面的程序使用 Fold 累计(accumulate)计算一个字符串数组的所有字符数目(total character count):

 

string[] names = { "Albert", "Burke", "Connor", "David",
                   
"Everett", "Frank", "George", "Harris"}
;

int count = names.Fold(0, (c, s) => c + s.Length);
// count == 46

 

除了(In addition to)这个有多种用途(general purpose)的 Fold 操作符之外,标准查询操作符(standard query operators)还包含一个多用途的 Count 操作符,和四个数字聚合(numeric aggregation)操作符(Min, Max, Sum, 和 Average),以简单化(simplify)这些普通的聚合操作(common aggregation operations)。数字聚合操作符检查(work over)数字类型(numeric types)(如 int, double, decimal)的序列,或者在一个方法(function)提供的时候检查任意值(arbitrary values)的序列(sequences),以映射(projects)序列的成员(members of the sequence)为一个数字类型(a numeric type)。

 

下面的程序阐明(illustrates)了刚才描述的 Sum 操作符的两个方面(both forms of):

 

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

string[] names = { "Albert", "Burke", "Connor", "David",

                   "Everett", "Frank", "George", "Harris"};

 

int total1 = numbers.Sum();            // total1 == 55

int total2 = names.Sum(s => s.Length); // total2 == 46

 

注意第二个使用 Sum 的语句与前面使用 Fold 的程序是相等的(equivalent to)。

 

 

  

 

待续, 错误难免,请批评指正,译者Naven 2005-10-24

posted on 2005-10-25 02:00 Javen-Studio 阅读(1328) 评论(0)  编辑 收藏 引用