LINQ包括生成運算符DefaultIfEmpty,Empty,Range&Repeat。Empty,Range和Repeat方法不是IEnumerable或IQueryable的擴展方法,而只是在靜態(tài)類Enumerable中定義的靜態(tài)方法。
方法 | 描述 |
---|---|
Empty | 返回一個空集合 |
Range | 從第一個元素開始,使用指定數(shù)量的具有順序值的元素生成IEnumerable <T>類型的集合。 |
Repeat | 生成具有指定元素數(shù)的IEnumerable <T>類型的集合,并且每個元素包含相同的指定值。 |
Empty()與其他LINQ方法一樣,該方法不是IEnumerable或IQueryable的擴展方法。它是Enumerable靜態(tài)類中包含的靜態(tài)方法。因此,您可以像其他靜態(tài)方法(如Enumerable.Empty <TResult>())一樣調(diào)用它。Empty()方法返回指定類型的空集合,如下所示。
var emptyCollection1 = Enumerable.Empty<string>(); var emptyCollection2 = Enumerable.Empty<Student>(); Console.WriteLine("Count: {0} ", emptyCollection1.Count()); Console.WriteLine("Type: {0} ", emptyCollection1.GetType().Name ); Console.WriteLine("Count: {0} ",emptyCollection2.Count()); Console.WriteLine("Type: {0} ", emptyCollection2.GetType().Name );
Type: String[] Count: 0 Type: Student[] Count: 0
Range()方法返回IEnumerable <T>類型的集合,該集合具有指定數(shù)量的元素和從第一個元素開始的順序值。
var intCollection = Enumerable.Range(10, 10); Console.WriteLine("總計數(shù): {0} ", intCollection.Count()); for(int i = 0; i < intCollection.Count(); i++) Console.WriteLine("值,索引位置為 {0} : {1}", i, intCollection.ElementAt(i));
總計數(shù): 10 值,索引位置為 0 : 10 值,索引位置為 1 : 11 值,索引位置為 2 : 12 值,索引位置為 3 : 13 值,索引位置為 4 : 14 值,索引位置為 5 : 15 值,索引位置為 6 : 16 值,索引位置為 7 : 17 值,索引位置為 8 : 18 值,索引位置為 9 : 19
在上面的示例中,Enumerable.Range(10, 10)創(chuàng)建了具有10個整數(shù)元素的集合,其順序值從10開始。第一個參數(shù)指定元素的起始值,第二個參數(shù)指定要創(chuàng)建的元素數(shù)。
Repeat()方法使用指定數(shù)量的元素生成IEnumerable <T>類型的集合,每個元素包含相同的指定值。
var intCollection = Enumerable.Repeat<int>(10, 10); Console.WriteLine("總數(shù): {0} ", intCollection.Count()); for(int i = 0; i < intCollection.Count(); i++) Console.WriteLine("值,索引位置為 {0} : {1}", i, intCollection.ElementAt(i));
總數(shù):10 值,索引位置為 0: 10 值,索引位置為 1: 10 值,索引位置為 2: 10 值,索引位置為 3: 10 值,索引位置為 4: 10 值,索引位置為 5: 10 值,索引位置為 6: 10 值,索引位置為 7: 10 值,索引位置為 8: 10 值,索引位置為 9: 10
在上面的示例中,Enumerable.Repeat<int>(10, 10) 創(chuàng)建具有100個重復(fù)值為10的整數(shù)類型元素的集合,第一個參數(shù)指定所有元素的值,第二個參數(shù)指定要創(chuàng)建的元素數(shù)。