Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C# (http://www.go4expert.com/articles/c-sharp-tutorials/)
-   -   Understanding LINQ Operators in C# With Examples (http://www.go4expert.com/articles/understanding-linq-operators-c-sharp-t30049/)

shabbir 7Apr2014 15:26

Understanding LINQ Operators in C# With Examples
 
LINQ is Microsoft’s latest data access technology. LINQ stands for language integrated query and it can be leverage to execute complex queries in a simple and more understandable manner. LINQ provides diverse query execution functions with the help of special methods that are known as query operators. In this article, we are going to throw light on some of the most important and useful query operators that can be used to perform almost all the routine data access tasks. If you are totally new to LINQ, you might need to look at our introductory articles on LINQ, particularly, Getting Started with LINQ and Interpreted LINQ queries. However, if you have basic knowledge of LINQ queries, and entity framework, you can continue reading this article.

On the basis of input and output, the LINQ standard query operators can be broadly classified into three categories as follows:

Sequence to Sequence



These are the most common standard query operators and perhaps most widely used as well. Sequences to sequence operators are further subdivided into following categories:
  1. Filtering Operators
  2. Projection Operator
  3. Ordering Operator
  4. Set Operators
  5. Conversion Operators

1. Filtering Operators



Filtering operators basically take a sequence as input, filter the sequence on the basis of some condition and returns the filtered sequence. These operators include:
  • Where
  • Skip
  • Distinct
  • Take
  • TakeWhile
  • SkipWhile
We will demonstrate the functionality of two of the above mentioned operators to explain the concept. We have used “Where” operators numerous times in our previous articles, so here we will use Take and Skip operators in our example. Have a look at our first example.

Example1
Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data.Entity;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {
            string[] cars = { "Toyota", "Audi", "Suzuki", "Honda", "Ford", "WolksWagon", "BMW", "Mercedez" };

            IEnumerable<string> carfil = cars.Take(3);
            foreach (string c in carfil)
            {
                Console.WriteLine(c);
            }

            Console.WriteLine("\n*************\n");

            carfil = cars.Skip(3);
            foreach (string c in carfil)
            {
                Console.WriteLine(c);
            }
            Console.ReadLine();
        }
    }
}

The code in Example1 is straight forward. We have a string type array which we named ‘cars’. Array implements the IEnumerable<T> interface; we know that on any type that implements the IEnumerable<T> interface, we can execute LINQ queries. The ‘cars’ array contain names of several cars in the form of string. In the next line, we created ‘carfil’ object of IEnumerable<T> interface. On the right side, we call Take operator on the ‘cars’ array. Take operator returns the first ‘n’ elements where ‘n’ is the integer parameter passed to it. We passed three to Take operator, therefore, names of the first three cars will be returned which we displayed using the foreach loop.

Next, we called the Skip operator which skips the ‘n’ number of elements from start of the collection. We passed it ‘3’, therefore it will skip the first three car names and will return the remaining. We again used for each loop to display the elements.

Note that in case of both Take operator and the Skip operator, the input was a sequence. And the output we got after the operator filtered our sequence is another sequence which is the case with Sequence to sequence operators. The output of the code in Example1 is as follows:

Output1

http://imgs.g4estatic.com/c-sharp/li...rs/output1.png

2. Projection Operator



These operators also take a sequence of collection as an input, perform projection on the items of the sequence, based on the predicate passed to it and return back the projected sequence. The two major projection operators are:
  • Select
  • SelectMany
Select and SelectMany operators are used to perform joins, cross joins when used with LINQ to SQL and EF. For now, we will illustrate the use of Select operator for projection on a collection of integers. Have a look at the second example of this article.

Example2
Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data.Entity;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {
            int[] numbers = { 1,2,3,4,5,6,7,8,9,10};

            IEnumerable<int> pronums = numbers.Select(n => n * n);

            foreach (int num in pronums)
            {
                Console.WriteLine(num);
            }
            Console.ReadLine();
        }
    }
}

Have a look at Example2. Here we have an array of integer which we named numbers and this array contains integers from 1 to 10. The line where projection is being done is as follows:
Code:

IEnumerable<int> pronums = numbers.Select(n => n * n);
Inside the Select operator, we have passed a predicate that return number after multiplying it with itself. In other words, return number after squaring it. What actually happening is that we are passing a sequence as input to Select operator and the Select operator is returning the corresponding values for each number after projecting the number. Unlike, filtering, we are not filtering a subset from input sequence; we are returning complete sequence back but after applying some projection on it. The output of the code in Example2 is as follows:

Output2

http://imgs.g4estatic.com/c-sharp/li...rs/output2.png

3. Ordering Operator



Ordering operators are used to modify the order of a sequence. It takes an input sequence, changes the order of the sequence and returns the sequence back. There are three ordering operators in LINQ:
  • OrderBy
  • ThenBy
  • Reverse
We will explain, OrderBy and Reverse with the help of our next Example. Have a look at it:

Example3
Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data.Entity;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {
            string[] cars = { "Toyota", "Audi", "Suzuki", "Honda", "Ford", "WolksWagon", "BMW", "Mercedez" };
            IEnumerable<string> carord = cars.OrderBy(c => c.Length).Reverse();

            foreach (string car in carord)
            {
                Console.WriteLine(car);
            }
            Console.ReadLine();
        }
    }
}

Again, we have cars collection as we had in Example1. But this time we are applying OrderBy operator on this sequence. The OrderBy operator takes a predicate as input and orders the elements of the sequence based on that predicate. In Example3, we have passed the predicate that order the elements of the ‘cars’ array based on their length, i.e. the length of the string. This will order the elements in the ascending order of the lengths of the string. But next, we have chained Reverse operator with the already ordered sequence. Reverse operator simply reverses the elements of the sequence. So now we have a sequence that has elements arranged in the descending order of the lengths of the strings. The first element will be the car name with most number of letters and the last element will be the car name with least number of characters. The output of the code in Example3 is as follows:

Output3

http://imgs.g4estatic.com/c-sharp/li...rs/output3.png

4. Set Operators



Set operators are sequence to sequence operators that take two sequences, perform sum functionality on these sequences and return the sequence. There are four major set operators.
  • Union
  • Intersect
  • Concat
  • Except
The usage of these four operators has been described in our next Example. Have a look at it.

Example4

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data.Entity;
namespace CSharpTutorial {
    class Program {
        public static void Main() {
            string[] cars = {
                "Toyota", "Audi", "Suzuki", "Honda", "Ford", "WolksWagon", "BMW", "Mercedez"
            }
            ;
            string[] cars2 = {
                "Toyota", "Audi", "Suzuki", "Honda"
            }
            ;
            Console.WriteLine("\nUsing concat operator ...\n");
            IEnumerable<string> carset = cars.Concat(cars2);
            foreach (string c in carset) {
                Console.Write(c +" ");
            }
            Console.WriteLine("\n\nUsing Union operator ...\n");
            carset = cars.Union(cars2);
            foreach (string c in carset) {
                Console.Write(c + " ");
            }
            Console.WriteLine("\n\nUsing Intersection operator ...\n");
            carset = cars.Intersect(cars2);
            foreach (string c in carset) {
                Console.Write(c + " ");
            }
            Console.WriteLine("\n\nUsing Except operator ...\n");
            carset = cars.Except(cars2);
            foreach (string c in carset) {
                Console.Write(c + " ");
            }
            Console.ReadLine();
        }
    }
}

Here we have two arrays cars and cars2. The array cars hold names of the cars while the cars2 array also holds names of some cars. The array cars2 is a subset of cars array. The Concat operator would simply append the elements of cars2 array after the cars array. The union method would take union of cars and cars2 array but since cars2 is a subset of cars array, the elements returned would be that of cars array. Similarly, intersection of cars and cars2 array would return elements of cars2 array. Finally the Except operator would return all the elements of cars array except those that are present in the cars2 array. The output of the code in Example4 is as follows:

Output4

http://imgs.g4estatic.com/c-sharp/li...rs/output4.png

5. Conversion Operators



Primarily, LINQ queries can be executed on all those collection types that implement the IEnumerable<T> interface. However, LINQ contain query operators that can be used one collection into other. There are two major conversion operators in LINQ.
  • Cast
  • OfType
These query operators are used to convert a non-generic collection to a generic collection that implement IEnumerable<T> interface and this new collection can be queried via other LINQ operators. Have a look at the 5th example of this article to better understand this concept.

Example5

Code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data.Entity;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {
            ArrayList numbers = new ArrayList() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            IEnumerable nums = numbers.Cast<int>();

            foreach (int n in nums)
            {
                Console.WriteLine(n);
            }

            string name = "James";
            numbers.Add(name);

            nums = numbers.OfType<int>();

            Console.WriteLine("\n Conversion Using OfType");
            foreach (int n in nums)
            {
                Console.WriteLine(n);
            }
            nums = numbers.Cast<int>();

            Console.WriteLine("\n Conversion Using Cast");
            foreach (int n in nums)
            {
                Console.WriteLine(n);
            }
            Console.ReadLine();
        }
    }
}

In our 5th example, we had an ArrayList collection which we named numbers. This collection is a non-generic collection and at the moment it contains integers from 1 to 9. We want to convert this non-generic collection int a generic collection. We have done this in the following line of code in Example5:
Code:

  IEnumerable nums = numbers.Cast<int>();
It will convert the non-generic numbers collection into a generic collection’nums’ of type integer. We have then enumerated upon the nums collection to display the items in the collection.

But the situation becomes interesting in case if a non-generic collection contains elements that are not of uniform type. For instance, in the non-generic ArrayList ‘numbers’ we can add element of data types other than integers. In Example5, we added a string type element ‘name’ in the numbers collection. Now, the numbers collection contains two types of elements, some integer values and a string type element.

Now if you try to convert this non-generic collection into a generic collection of type integer, the Cast and the OfType operator would behave differently. The Cast operator would throw casting exception, while when we use OfType operator to convert such non-generic collections into generic counterpart, it will ignore the element whose type doesn’t match with the type of the generic collection. So, the ‘name’ element of type string would be ignored while only the integer elements would be copied to the generic collection. The output of the code in Example5 is as follows:

Output5

http://imgs.g4estatic.com/c-sharp/li...rs/output5.png

You will see the following output, with the casting exception as follows:

http://imgs.g4estatic.com/c-sharp/li...ators/fig1.png

Another important thing to note while using these conversion operators is that, they do not work like traditional cast operators. For instance you cannot use Cast and OfType operators to perform numeric conversions or the custom conversions. This concept is elaborated with the help of our next example.

Example6

Code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data.Entity;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {
            int num = 6;   
            long lnum = 6; // Implicit coversion from int to long
            int num2 = (int)lnum; // Explicit conversion from long to int

            int[] numbers = {1,2,3,4,5,6,7,8,9};
            IEnumerable<long> longnum = numbers.OfType<long>();
            Console.WriteLine(longnum.Count());

            longnum = numbers.Cast<long>();
            Console.WriteLine(longnum.Count());

            Console.ReadLine();
        }
    }
}

In Example6, we have first shown that how conventional casting is done. Next we have a numbers array which contains integers from 1 to 9. This numbers array is of type integer. First we have tried to cast this number array into long array using OfType operator. The Oftype operator would not cast the numbers array from int to long and it will emit zero. On the other hand if, Cast operator is used to perform this type of casting it will throw InvalidCastException. The output of the code is as follows:

Output6

http://imgs.g4estatic.com/c-sharp/li...rs/output6.png

http://imgs.g4estatic.com/c-sharp/li...ators/fig2.png

Sequence to Element Operators



As aforementioned, sequence to element operators are those operators that take a sequence as an input and return an element based on the functionality of the operator. Following are some of the most important sequence to element operators.
  • First
  • Last
  • Single
  • ElementAt
  • FirstOrDefault
  • LastOrDefault
  • SingleOrDefault
  • ElementAtOrDefault
  • DefaultIfEmpty

More sequence to element operators
  1. Aggregation Methods
  2. Quantifiers
An important point to note here is that all the methods that end with OrDefault return the default value for the type if the sequence doesn’t contain any element that matches the specified predicate or the sequence is empty. The default value for all the reference types is null, for all numeric types is zero and for all bool types is false.

In our next example, I am going to show you the usage of First, FirstOrDefault, Last and LastOrDefault. Have a look at the 7th example.

Example7

Code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data.Entity;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {
            string[] cars = { "Toyota", "Audi", "Suzuki", "Honda", "Ford", "WolksWagon", "BMW", "Mercedez" };

            string first = cars.First();
            string last = cars.Last();

            string firsti = cars.First(c=>c.Contains("i"));
            string lasto = cars.Last(c=>c.Contains("o"));

            string firstordefault = cars.FirstOrDefault(c=>c.EndsWith("e"));
            string lastordefault = cars.LastOrDefault(c => c.StartsWith("z"));

            Console.WriteLine("First Element: "+first);
            Console.WriteLine("Last Element: "+last);
            Console.WriteLine("First containing i: "+firsti);
            Console.WriteLine("Last Containing o: " + lasto);
            Console.WriteLine("First or Default ending with e: " + firstordefault);
            Console.WriteLine("Last or default ending with z: " + lastordefault);

            Console.ReadLine();
        }
    }
}

Here in Example7, we have string cars similar to what we have in Example1. We have called First and Last operator to get the first and last element of the array. Then we have demonstrated that you can also pass a predicate to First and Last operators and the returned value would be according to that predicate. For instance, we passed the predicate that return first element from the cars array that contains ‘i’ in it. Similarly, we passed the predicate to Last operator that it should return that last element which contains ‘o’.

Next, we have demonstrated the use of FirstOrDefault and LastOrDefault operator. We have passed the predicate to FirstOrDefault that return first element from the cars array that ends with ‘e’. Similarly, we have passed the predicate to LastOrDefault that return the last element of the cars array that ends with ‘z’. There are no elements that end with ‘e’ or ‘z’. So both FirstOrDefaul and LastOrDefault would return the default value for string data type which would be null. If you look at the output of the code in Example7, it should look like this:

Output7

http://imgs.g4estatic.com/c-sharp/li...rs/output7.png

You can see from the output that FirstOrDefault ending with ‘e’ and LastOrDefault ending with ‘z’ returns nothing.

In our next Example, we are going to demonstrate the use of Single, SingleOrDefault and ElementAt operators. Have a look at the 8th Example of this article.

Example8

Code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data.Entity;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {
            string[] cars = { "Toyota", "Audi", "Suzuki", "Honda", "Ford", "WolksWagon", "BMW", "Mercedez" };

          string name = cars.Single(c=>c.EndsWith("W"));
            string name2 = cars.SingleOrDefault(c=>c.EndsWith("o"));

            string element = cars.ElementAt(3);

            Console.WriteLine("Single name ending with W: " + name);
            Console.WriteLine("Single or default ending with o: "+name2);
            Console.WriteLine("Element at 3rd index: "+element);

            Console.ReadLine();
        }
    }
}

Single operator returns exactly single element that matches the specified predicate. If more than one element matches the predicates, an error occurs. Usually Single operator is used to get a single record from a database table based on the key. SingleOrDefault works like FirstOrDefault or LastOrDefault. The ElementAt returns the element at the specified index, the index starts from 0. The output of the code in Example8 is follows:

Output8

http://imgs.g4estatic.com/c-sharp/li...rs/output8.png

Aggregation Methods



Aggregation operators are a type of sequence to elements operators. These operators take sequence of elements as input and return a scalar value after performing aggregate function on the sequence of elements. Major aggregation operators are:
  • Count
  • Min
  • Max
  • Average
  • Sum
  • LongCount
  • Aggregate
As we have previously done, we will explain these operators with the help of an example. In our next example, we will see how Count, Min and Max operators work. Have a look at the 9th example of this tutorial.

Example9
Code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data.Entity;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {
            int[] numbers = { 1,5,7,3,6,9,4,2,5,11,2, 25 };

          int min = numbers.Min();
          int max = numbers.Max();
          int nums = numbers.Count();

          Console.WriteLine(min);
          Console.WriteLine(max);
          Console.WriteLine(nums);

          Console.ReadLine();
        }
    }
}

This is perhaps the easiest example of this tutorial. We have an array which we named numbers. This array is of type integer and it contains some random integer values. The Min operator returns the smallest value of the array, the Max operator returns the largest element in the sequence whereas the Count operator returns the number of elements in the sequence. The longCount is similar in functionality but it returns a 64 bit integer and can be used to count to up to 64 billion elements in the sequence. The output of the code in Example9 is as follows:

Output9

http://imgs.g4estatic.com/c-sharp/li...rs/output9.png

Next, we are going to explain the usage of Sum and Average operators. Out next example demonstrates this concept. Have a look at our 10th example:

Example10

Code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data.Entity;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {
            int[] numbers = { 1,5,7,3,6,9,4,2,5,11,2, 25 };

            int sum = numbers.Sum();
            int average = (int)numbers.Average();

            string[] cars = { "Toyota", "Audi", "Suzuki", "Honda", "Ford", "WolksWagon", "BMW", "Mercedez" };

            int sum2 = cars.Sum(c => c.Length);

            Console.WriteLine("Sum of numbers in numbers array: " + sum);
            Console.WriteLine("Average of numbers in numbers array: " + average);
            Console.WriteLine("Sum of lengths of all the strings in car array: " + sum2);

          Console.ReadLine();
        }
    }
}

In our 10th example, we have a numbers array of some random numbers. We first used Sum operators to calculate the sum of all the elements in the array. Next we calculated the average of all the numbers in the numbers array by using Average operator.

The next lines of code are particularly interesting, we have a string array named cars and we want to calculate the sum of lengths of all the strings in this cars array. To do this, we passed a predicate to the Sum operator that addition should be between the lengths of the elements of the cars array. Using this technique you can also calculate the average of the lengths of the strings in cars array. The output of the code in Example10 is as follows:

Output10

http://imgs.g4estatic.com/c-sharp/li...s/output10.png

It can be seen in the output that first, the sum of all the numbers in the numbers array has been displayed. Next, the integer value of the average of all the numbers in the numbers array has been displayed. Finally, the sum of the lengths of all the strings in the cars array has been displayed.

Quantifiers



Quantifiers are types of sequence to elements operators. Unlike aggregation operators that returned a single element, quantifiers return a bool value. The major operators in LINQ are:
  • Any
  • Contains
  • All
  • SequenceEqual
In our next Example, we are going to explain Any and Contains operators. The 11th example of this article demonstrates this concept. Have a look at the code in Example11.

Example11

Code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data.Entity;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {
            string[] cars = { "Toyota", "Audi", "Suzuki", "Honda", "Ford", "WolksWagon", "BMW", "Mercedez" };

            bool any = cars.Any(c =>c.EndsWith("n"));
            bool contains = cars.Contains("Audii");

            Console.WriteLine("Any car that ends with n:"+any);
            Console.WriteLine("Cars array contains Auddi:"+contains);

            int[] numbers = { 1, 5, 2, 7, 1, 2, 11, 23, 45, 12, };
            Console.WriteLine(numbers.Any(n=>n>20));

          Console.ReadLine();
        }
    }
}

In our Example11, first we have a string type array which we named cars. This array contains several strings which are actually representing the names of the cars. On this cars array collection, we have called Any operator and passed it a predicate that if the cars array contains any element that ends with ‘n’. If there is an element that is ending with ‘n’, Any operator would return true otherwise it will return false. If you do not pass any predicate to Any operator, it will just check if the collection is empty. If collection is empty, Any will return false, otherwise it will return true if collection contains some elements in it. An important point to note here is that Any operator only checks for at least one element that satisfies the predicate. For instance, there can be more than one element that ends with ‘n’, but as soon as the Any operator finds first element, it returns true because it only looks for one element that satisfies its predicate.

Next in our Example11, we have demonstrated the use of Contains operator. Contains operator returns true if the collection contains the element that is passed as parameter to the Contains operator. We have passed ‘Audii’ as parameter and since the cars collection doesn’t have any element with this name. It will return false.

We have then demonstrated the usage of Any operator once more, but this time with an integer array. We passed the predicate to the Any operator that if the numbers array contains any value that is greater than 20. We have a value greater than 20 in our numbers collection; therefore this Any operator would again return true which we have displayed on the console. The output of the code in Example11 is as follows:

Output11

http://imgs.g4estatic.com/c-sharp/li...s/output11.png

As we programmed, the output shows that there is at least one element in cars collection that ends with ‘n’. Similarly, the cars collection do not contain any element “Audi” and a ‘True’ at the end of the output shows that there was at least one element in numbers array which was greater than 20.

Nothing to Sequence Operators



As we mentioned at the start of the article, the third major type of LINQ operators is the operators that don’t take any input but they return a sequence. These operators are also commonly referred as generation methods. There are three basic generation methods:
  • Empty
  • Repeat
  • Range
These methods are basically static methods and they only take a type argument as an input. In the 12th example of this article, I am going to explain you the Empty operator and its advantages. Have a look at Example12.

Example12

Code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data.Entity;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {
            foreach (string str in Enumerable.Empty<string>())
            {
                Console.WriteLine(str); // Nothing will be displayed
            }

            int[][] numbers = {  new [] {1,5,6,4},
                                  new [] {1,5 },
                                  null
                              };

            IEnumerable<int> numflat = numbers.SelectMany(n=>n ?? Enumerable.Empty<int>());

            foreach(int num in numflat)
            {
            Console.WriteLine(num);
            }
          Console.ReadLine();
        }
    }
}

In 12th Example, we have first created an empty sequence of string. A very important use of Empty operator is when you want to flat jagged arrays. If you use SelecetMany operator without the ‘??’ followed by the Empty operator, jagged arrays that contain any inner array which is null, an error is generated and jagged array can’t be flattened. However, using Select many with ‘??’ followed by empty operator solves this issue. If you compile the above code, you will see elements of all the inner arrays flattened. The output of the code in Example12 is as follows:

Output12

http://imgs.g4estatic.com/c-sharp/li...s/output12.png

The two other generation methods are Range and Repeat. Range takes two parameters, the first one is the starting element followed by the number of incremented elements. Repeat also takes two parameters, the first is the element to repeat and the second parameter is the number of times the element should be repeated. Our last example demonstrates this concept. Have a look at 13th example of this tutorial.

Example13
Code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data.Entity;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {

            IEnumerable<int> numbers = Enumerable.Range(10,5);
            foreach(int num in numbers)
            {
            Console.Write(num +" ");
            }

            numbers = Enumerable.Repeat(5, 5);
            Console.WriteLine("\n");
            foreach (int num in numbers)
            {
                Console.Write(num + " ");
            }
          Console.ReadLine();
        }
    }
}

Output13

http://imgs.g4estatic.com/c-sharp/li...s/output13.png


All times are GMT +5.5. The time now is 11:16.