Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

C# Program to Print Only Those Numbers Whose Value is Less Than Average of all Elements in an Integer Array using LINQ

  • Last Updated : 18 Oct, 2021

Language-Integrated Query (LINQ) is a uniform query syntax in C# to retrieve data from different sources. It eliminates the mismatch between programming languages and databases and also provides a single querying interface for different types of data sources. In this article, we will learn how to print only those numbers whose value is less than the average of all elements in an integer array using LINQ in C#.

Example:

Input: 464, 23, 123, 456, 765, 345, 896, 13, 4
Output: Average is 343
So the numbers less than the average are:
23 123 13 4 

Input: 264, 3, 223, 556, 1, 965, 145, 2, 14
Output: Average is 241
So the numbers less than the average are:
3 223 1 145 2 14

Approach: 

To print only those numbers whose value is less than average of all elements in an array we use the following approach: 

  • Store integer(input) in an array.
  • The sum of the elements is calculated using the Sum() method.
  • The average of the array is calculated by dividing the sum by the length of the array.
  • By using the LINQ query we will store the numbers less than the average of the array in an iterator.
  • Now the iterator is iterated and the integers are printed.

Example:

C#




// C# program to display only those numbers whose value is
// less than average of all elements in an array using LINQ
using System;
using System.Linq;
  
class GFG{
      
static void Main()
{
      
    // Storing integers in an array
    int[] Arr = { 464, 23, 123, 456, 765, 345, 896, 13, 4 };
    
    // Find the sum of array
    int total = Arr.Sum();
      
    // Find the average of array
    int avg = total / Arr.Length;
      
    // Store the numbers in an iterator
    var nums = from num in Arr where num < avg select num;
      
    // Display the result
    Console.WriteLine("Average is " + avg);
    Console.WriteLine("The Numbers:");
    foreach(int n in nums)
    {
        Console.Write(n + " ");
    }
    Console.WriteLine();
}
}

Output:

Average is 343
The Numbers:
23 123 13 4 
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!