Linq 整理(二)

* 聚合操作符:Aggregate、Average、Count、LongCount、Max、Min和Sum
Enumerable.Aggregate 方法可简化在值序列上执行的计算
 
1)Aggregate<TSource>(IEnumerable<TSource>, Func<TSource, TSource, TSource>) 
工作方式:调用一次 func 在source中除第一个元素外的每个元素。 每次调用 func 时,该方法都将传递序列中的元素聚合值(作为 func 的第一个参数)。 将 source 的第一个元素用作聚合的初始值。 用 func 的结果替换以前的聚合值。 该方法将返回 func 的最终结果。
 
例:string sentence = "the quick brown fox jumps over the lazy dog";
      string[] words = sentence.Split(' ');
      string reversed = words.Aggregate((workingSentence, next) => next + " " + workingSentence);
      //result: dog lazy the over jumps fox brown quick the
 
2)Aggregate<TSource, TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>) 
工作方式:对 source 中的每个元素调用一次 func。 每次调用 func 时,该方法都将传递序列中的元素聚合值(作为 func 的第一个参数)。 将 seed 参数的值用作聚合的初始值。 用 func 的结果替换以前的聚合值。 发方法将返回 func 的最终结果。(和上面大同小异)
 
例:int[] ints = { 4, 8, 8, 3, 9, 0, 7, 8, 2 };
      int numEven = ints.Aggregate(0,
                                                  (total, next) => next % 2 == 0 ? total + 1 : total); 
      //result: 6
 
3)Aggregate<TSource, TAccumulate, TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>, Func<TAccumulate, TResult>) 
工作方式:对 source 中的每个元素调用一次 func。 每次调用 func 时,该方法都将传递序列中的元素聚合值(作为 func 的第一个参数)。 将 seed 参数的值用作聚合的初始值。 用 func 的结果替换以前的聚合值。 将 func 的最终结果传递给 resultSelector 以获取该方法的最终结果
 
例:string[] fruits = { "apple", "mango", "orange", "passionfruit", "grape" };
      string longestName = fruits.Aggregate("banana", 
                                                                (longest, next) => next.Length > longest.Length ? next : longest, 
                                                                fruit => fruit.ToUpper()); 
      //result: PASSIONFRUIT
 
* 集合操作符:Distinct,Except,Intersect和Union
 
* 生成操作符:Empty,DefaultIfEmpty,Range和Repeat
1)Empty:返回一个具有指定的类型参数的空 IEnumerable<T>
2)DefaultIfEmpty:返回 IEnumerable<T> 的元素;如果序列为空,则返回一个具有默认值的单一实例集合
 
Enumerable.DefaultIfEmpty<TSource> 方法 (IEnumerable<TSource>)
List<int> numbers = new List<int>();
foreach (int number in numbers.DefaultIfEmpty())
{
    Console.WriteLine(number);
}
 
Enumerable.DefaultIfEmpty<TSource> 方法 (IEnumerable<TSource>, TSource)
Pet defaultPet = new Pet { Name = "Default Pet", Age = 0 };
List<Pet> pets = new List<Pet>();
foreach (Pet pet in pets.DefaultIfEmpty(defaultPet))
{
    Console.WriteLine("\nName: {0}", pet.Name);
}
 
3)Range:生成指定范围内的整数的序列
IEnumerable<int> squares = Enumerable.Range(1, 10)
 
4)Repeat:生成包含一个重复值的序列
IEnumerable<string> strings = Enumerable.Repeat("I like programming.", 15);
posted @ 2014-10-22 15:02  clark wei  阅读(111)  评论(0编辑  收藏  举报