Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

How do I find the value at a certain position in an Array in C#?

I need to iterate through an Array and find the sum of the odd, and the even positioned values.

Here is what I have, but I'm getting the error: Cannot apply indexing with [] to an expression of type 'Array'

static void SumOfOddsAndEvens(Array arr)
        {
            int i = 0;
            bool isEven = true;
            int evenSum = 0;
            int oddSum = 0;

            while (i < arr.Length)
            {
                Console.WriteLine(arr[i]);

                if (isEven) evenSum += arr[i]; // Cannot apply indexing with [] to an expression of type 'Array'
                if (!isEven) oddSum += arr[i];
                isEven = !isEven;
                i++;
            }

            Console.WriteLine("Sum of even slots: " + evenSum);

            Console.WriteLine("Sum of odd slots: " + oddSum);
        }

Function is being called here:

 static void Main(string[] args)
        {
            SumOfOddsAndEvens(new int[] { 1, 2, 3, 4, 6, 7, 8 });
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Although all arrays in C# derive from the base-class Array, the latter does not define an indexer. Thus you can′t use arr[i] when arr is just an Array.

However I wonder why you even use that base-class, instead of the actual one, which is int[] in your case:

static void SumOfOddsAndEvens(int[] arr)
{
    int i = 0;
    bool isEven = true;
    int evenSum = 0;
    int oddSum = 0;

    while (i < arr.Length)
    {
        Console.WriteLine(arr[i]);

        if (isEven) evenSum += arr[i];
        if (!isEven) oddSum += arr[i];
        isEven = !isEven;
        i++;
    }

    Console.WriteLine("Sum of even slots: " + evenSum);

    Console.WriteLine("Sum of odd slots: " + oddSum);
}

Using the base-class would also allow the following, which is pure non-sense:

SumOfOddAndEvens(new[] { "Hello",  "World" };

or even this:

SumOfOddAndEvens(new object[] { 1, "World" };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...