Here I am considering count operation has to be performed on array. As we know that if sum of specific elements of array is to be found, then we have to iterate the array and check whether element of the array satisfies the predicate or not. If it satisfies then increase the count else ignore it. But how is it, if I say that we need not to iterate the array to find the count or any such kind of operations.
Consider an integer array (arr is an array for our code) having n elements. we have to find out how many elements are there which are greater than or equals to 75.
What, if we can write SQL like query in C# also to perform these kind of operations. LINQ introduced in .net framework 3.5, provides us such facilities.
Consider an integer array (arr is an array for our code) having n elements. we have to find out how many elements are there which are greater than or equals to 75.
Iteration method to find the count
int count = 0;
for (int i = 0; i
< arr.Length; i++)
if (arr[i] >= 75) count++;
LINQ for above Operation
var count = (from ele in arr
where ele >=75
select ele).Count();
In both above method count will contain the count of number of elements in array which are greater than or equals to 75.
No comments:
Post a Comment