Reputation: 1059
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
Upvotes: 3
Views: 2990
Reputation: 1160
I found this looking for an answer to the same problem, but the List collection was easier for me.
List<string[]> array2Db = new List<string[]>() {
new string[] { "one", "two" },
new string[] { "three", "four" },
new string[] { "five", "six" }
};
calculate(array2Db[2]);
Upvotes: 0
Reputation: 3576
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
Upvotes: 1
Reputation: 5121
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());
Upvotes: 6
Reputation: 29016
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
Upvotes: 2