C# 使用 LINQ 仅打印整数数组中所有元素的值小于平均值的数字
语言集成查询 (LINQ) 是 C# 中用于从不同来源检索数据的统一查询语法。它消除了编程语言和数据库之间的不匹配,还为不同类型的数据源提供了单一的查询接口。在本文中,我们将学习如何使用 C# 中的 LINQ 仅打印值小于整数数组中所有元素的平均值的数字。
例子:
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
方法:
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.
例子:
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();
}
}
输出:
Average is 343
The Numbers:
23 123 13 4