How to find value index and array it belongs within a group of multiple arrays in C#

Viewed 51

I have 4 arrays, each holds different values relating to hours of the day thus:

int[] HourArray1 = {00, 04, 08, 12, 16, 20};
int[] HourArray2 = {01, 05, 09, 13, 17, 21};
int[] HourArray3 = {02, 06, 10, 14, 18, 22};
int[] HourArray4 = {03, 07, 11, 15, 19, 23};

Belo is what I have been able to do to get the index of a particular hour and the array where it is located.

       private void btnGetHexValue_Click(object sender, EventArgs e)
    {
        int HourIndex = 0;
        int HourGroup = 0;

        // Hours
        HourIndex = Array.IndexOf(HourArray1, Convert.ToInt32(DateTime.Now.ToString("HH")));
        HourGroup++;

        if (HourIndex == -1)
        {
            HourIndex = Array.IndexOf(HourArray2, Convert.ToInt32(DateTime.Now.ToString("HH")));
            HourGroup++;

            if (HourIndex == -1)
            {
                HourIndex = Array.IndexOf(HourArray3, Convert.ToInt32(DateTime.Now.ToString("HH")));
                HourGroup++;

                if (HourIndex == -1)
                {
                    HourIndex = Array.IndexOf(HourArray4, Convert.ToInt32(DateTime.Now.ToString("HH")));
                    HourGroup++;
                }
            }
    

My request: Is there a better and more efficient approach please?

Many thanks in advance.

1 Answers

You can put the arrays into another array and use a single LINQ query:

int[][] allHours = { HourArray1, HourArray2, HourArray3, HourArray4 };
(int hourIndex, int hourGroup) = allHours
        .Select((arr, ix) => (Position: ix + 1, FoundIndex: Array.IndexOf(arr, DateTime.Now.Hour)))
        .Where(x => x.FoundIndex >= 0)
        .Select(x => (x.FoundIndex, x.Position))
        .DefaultIfEmpty((-1, -1))
        .First();

Demo: https://dotnetfiddle.net/ACDrz9

Related