简体   繁体   中英

Sending one row of a 2D array to a function in c#

I am new to C# and trying to learn how to send individual rows of a 2D array to a function. I have a two-dimensional array of 3 rows and 2 columns. If I want to send my third row to a function called calculate , can you please tell me how to do this.

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" }, { "five", "six" } };
            calculate(array2Db[2,0]); //I want to send only the 3rd row to this array
            //This array may contain millions of words. Therefore, I can't pass each array value individually
        }

        void calculate(string[] words)
        {
            for (int i = 0; i < 2; i++)
            {
                Console.WriteLine(words);
            }
        }
    }
}

Any help would be greatly appreciated

You could make an extension method that will enumerate you the specific row.

public static class ArrayExtensions
{
    public static IEnumerable<T> GetRow<T>(this T[,] items, int row)
    {
        for (var i = 0; i < items.GetLength(1); i++)
        {
            yield return items[row, i];
        }
    }
} 

Then you can use it with

string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" }, { "five", "six" } };
calculate(array2Db.GetRow(2).ToArray());

array2Db[2, 0] will give you a single value at the third row first column, which is a string actually, not an array as the method calculate is expecting, If you want to pass the complete row means you have to call the method like the following:

calculate(new []{array2Db[2, 0],array2Db[2, 1]});

Which will pass the two columns of the third row as an array to the called method. A working Example here

Using the length of the 'Y' dimension (x = 0, y = 1) we create an Enumerable of numbers between 0 and Y's length, which will serve as a loop to iterate and retrieve all the elements where the 'X' dimension = 2 (3rd in a 0-based collection)

var yRange = Enumerable.Range(0, array2Db.GetLength(1));
var result = yRange.Select(y => array2Db[2, y]);

Or in your case (I changed the parameter received by calculate() from string array to IEnumerable to avoid pointless type conversion:

calculate(Enumerable.Range(0, array2Db.GetLength(1)).Select(y => array2Db[2, y]));

static void calculate(IEnumerable<string> words)
{
    foreach(string word in words)
        Console.WriteLine(word);
}

EDIT: tried to add some clarification

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM