Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to get the count of an element in an array within specified range

Tags:

arrays

c#

vb.net

If I have an ArrayList called holder: {2,3,3,5,4,7,1,7,8,4}. Let say I wanted to find the count of certain element's occurrence in the above array within a certain range, I have these function:

In VB.Net:

Private Function getValInRange(ByVal lowerVal As Integer, ByVal upperVal As Integer, ByVal holder As ArrayList) As Integer
        Dim count As Integer = 0
        For Each item As Integer In holder
            If (item <= upperVal AndAlso item >= lowerVal) Then
                count = count + 1
            End If
        Next
        Return count
End Function

In C#:

private int getValInRange(int lowerVal, int upperVal, ArrayList holder)
{
    int count = 0;
    foreach (int item in holder)
    {
        if ((item <= upperVal && item >= lowerVal))
        {
            count = count + 1;
        }
    }

    return count;
}

So, when I query count = getValInRange(3,5,holder), I shall get a return of 5

I know the above function will be able to satisfy my needs, but I wonder if there is already a built in function that I can use. I plan to clean up my code and learn at the same time. Thanks a lot...

like image 239
Hari Avatar asked Jan 24 '26 10:01

Hari


1 Answers

I don't think there is such a built-in method in .NET Core, but you can write this more concisely, using Enumerable.Where.

 holder.Cast<int>().Where(x => x <= upperLimit && x >= lowerLimit).Count()

ArrayList is actually obsolete. If you don't have to stick with it, try changing to a List<int>. That way, you don't need the call to Cast:

 holder.Where(x => x <= upperLimit && x >= lowerLimit).Count()

Alternatively,

 holder.Count(x => x <= upperLimit && x >= lowerLimit)

The x => ... thing, if you didn't know, is called a lambda expression, learn more about them here.

There are lots of other cool methods that help you with dealing with IEnumerable<T> in the System.Linq namespace! This cool collection of helper methods is called Language INtegrated Query (LINQ).

like image 70
Sweeper Avatar answered Jan 25 '26 23:01

Sweeper