abhi
abhi

Reputation: 29

Working with index, local variable and class

In the code below, I am trying to use indexing with item.Number It looks like I cannot compare if (item.Number[index] == decimalNumbers[j]) like this and getting the error "c# cannot apply indexing with [] to an expression of type 'int'"

If anyone can guide me to the right direction. Also, code is not a complete code. I just want to understand the reasoning.

public class NumberWithDifference
{
    public int Number { get; set; }
    public static int[] decimalNumbers = new int[10]{0,1,2,3,4,5,6,7,8,9};

    foreach (var item in jagged.Items)
    {
        i = true;
        int index = 0;
        var a = item.Number;

        for (int j = 0; j < decimalNumbers.Length; j++)
        {
            if (item.Number[index] == decimalNumbers[j])
            {
                Console.Write(decimalNumbers[j]);
                i = false;

                if (index < item.Number.Length - 1)
                        index++;
            }

            else
            {
                Console.Write(0);
            }
    }
}

Upvotes: 0

Views: 269

Answers (1)

Kei
Kei

Reputation: 1026

As the error message states, item.Number is an int. Indexing can be applied to an array or list of ints, but not to a single int value.

Thus, this code below,

if (item.Number[index] == decimalNumbers[j])

should really be

if (item.Number == decimalNumbers[j])

Assuming jagged is an array of NumberWithDifference, you could also do the following instead:

for (int j = 0; j < decimalNumbers.Length; j++)
{
    if (jagged[index].Number == decimalNumbers[j])
    {
        etc...

Upvotes: 2

Related Questions