We can count numbers with Enumerable class in C# Linq
Example 1: In first example, we create an enumerable object filled numbers that are 1 to 100 numbers. Then we iterate numbers that are added into enumerable object.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | using System; using System.Collections.Generic; using System.Linq; namespace CSharpConsoleExamples { class Program { public static void Main() { //Printing 1 to 100 in C# Linq IEnumerable<int> numbers = Enumerable.Range(1, 100); foreach (int n in numbers) { Console.Write(n +" "); } Console.ReadLine(); } } } |
Example 2: Converting Enumerable to List in C# Linq
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | using System; using System.Collections.Generic; using System.Linq; namespace CSharpConsoleExamples { class Program { public static void Main() { IEnumerable<int> enumerable = Enumerable.Range(1, 100); List<int> numbers = enumerable.ToList(); numbers.ForEach(e => Console.Write(e + " ")); Console.ReadLine(); } } } |
Example 2.1: short spelling
1 2 3 4 5 6 7 8 9 10 11 12 | class Program { public static void Main() { List<int> numbers = Enumerable.Range(1, 100).ToList(); numbers.ForEach(e => Console.Write(e + " ")); Console.ReadLine(); } } |
Output: