操作符:Count
原型:
public static int Count<TSource>( this IEnumerable<TSource> source )
public static int Count<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate )
描述:返回输入序列的个数。如果输入序列实现了ICollection接口,则直接返回ICollection的Count属性, 如果没有,则遍历序列的元素。
操作符:Sum
原型:
public static Numeric Sum( this IEnumerable<Numeric> source);
public static Numeric Sum<T>( this IEnumerable<T> source, Func<T, Numeric> selector);
描述:返回输入序列的数值的和。如果我们查看msdn,会发现他包含了20种原型,归结起来,就是上面那2中,其中,Numeric可以是Single,int,long,double,decimal以及其对应的可空类型。
操作符:Min
原型:
public static Numeric Min( this IEnumerable<Numeric> source);
public static T Min<T>( this IEnumerable<T> source);
public static Numeric Min<T>( this IEnumerable<T> source, Func<T, Numeric> selector);
public static S Min<T, S>( this IEnumerable<T> source, Func<T, S> selector);
描述:Min操作符包含2中原型,其中,第一种和第三种原型Numeric的取值跟Sum的是一样的,对于第二种原型和第四种原型, 如果T是自定义类型,我们需要为T实现IComparable接口。举个例子:
public class Pet:IComparable<Pet> { public string Name { get; set; } public int Age { get; set; } public int CompareTo(Pet other) { if (other.Age > this.Age) return -1; else if (this.Age == other.Age) return 0; else return 1; } }
List<Pet> pets = new List<Pet>() {new Pet {Name = "Terry", Age = 12}, new Pet{Name="Adam",Age = 15}, new Pet{Name="Tina",Age = 9} }; Pet yongestPet = pets.Min(); Console.WriteLine(yongestPet.Name);
返回的结果是:
Tina
操作符:Max
原型:
描述:与Min类似
操作符:Average
原型:
public static Result Average( this IEnumerable<Numeric> source);
public static Result Average<T>( this IEnumerable<T> source, Func<T, Numeric> selector);
描述:如果Numeric为int或long,则Result为double,如果Numeric为int?或long?,则Result为double?,其余Result和Numeric同类型。
操作符:Aggregate
原型:
public static TSource Aggregate<TSource>( this IEnumerable<TSource> source, Func<TSource, TSource, TSource> func )
public static TAccumulate Aggregate<TSource, TAccumulate>( this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func )
public static TResult Aggregate<TSource, TAccumulate, TResult>( this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func, Func<TAccumulate, TResult> resultSelector )
描述:对一个序列进行累加。
原型一的例子(from msdn):
string sentence = "the quick brown fox jumps over the lazy dog"; // Split the string into individual words. string[] words = sentence.Split(' '); // Prepend each word to the beginning of the // new sentence to reverse the word order. string reversed = words.Aggregate((workingSentence, next) => next + " " + workingSentence); Console.WriteLine(reversed);
对于输入序列的每一个元素,都会应用func方法,累计后的值作为第一个参数,下一个元素作为第二个参数。
对于原型二,我们提供了一个seed参数,作为累计的起始值,也就是说,第一次累计的结果是seed+TAccumulate,举个例子:
int [] ints = { 4, 8, 8, 3, 9, 0, 7, 8, 2 }; // Count the even numbers in the array, using a seed value of 0. int numEven = ints.Aggregate(10, (total, next) => next % 2 == 0 ? total + 1 : total); Console.WriteLine("The number of even integers is: {0}", numEven);
输出的结果是16,因为我们的起始值设定为10,而输入序列中,偶数的个数为6个。