C# - Print all numbers greater than a given number in an array using LINQ

Learn, how to print all numbers greater than a given number in an array using LINQ in C#. By Nidhi Last updated : April 01, 2023

Here we will create an integer array that contains multiple integer numbers then we print only those numbers from the array that are greater than 786 using LINQ and print them on the console screen.

C# program to print all numbers greater than a given number in an array using LINQ

The source code to print numbers greater than 786 in an integer array using LINQ in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//Program to print the numbers greater than 786 
//in an integer array using LINQ in C#.

using System;
using System.Linq;

class Number {
  static void Main() {
    int[] intArr = {123, 456, 789, 012, 345, 567, 890};

    var nums = from num in intArr
    where num > 786
    select num;

    Console.WriteLine("Numbers are :");
    foreach(int n in nums) {
      Console.Write("{0} ", n);
    }
    Console.WriteLine();
  }
}

Output

Numbers are :
789 890
Press any key to continue . . .

Explanation

In the above program, we created a class Number that contains the Main() method.

int[] intArr = {123,456,789,012,345,567,890};

In the Main() method we created an integer array that contains multiple numbers.

var nums = from num in intArr
where num > 786
select num;

In the above code, we select numbers greater than 786 from integer array.

Console.WriteLine("Numbers are :");
foreach (int n in nums)
{
    Console.Write("{0} ",n);
}
Console.WriteLine();

In the above code, we printed the numbers selected from the LINQ query on the console screen.

C# LINQ Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.