C# 2D Array calling it another class through obj.method(); - c#

Write a Java class that has a static method named count that accepts a 2D-Array of integers and a target integer value as parameters and returns the number of occurrences of the target value in the array. For example, if a variable named list refers to an array containing values {{3,5,7,94}{5,6,3,50}} then the call of count(list, 3) should return 2 because there are 2 occurrences of the value 3 in the array.
Here is my coding and it's not giving me proper output
P.S :-I have been told to take count method as public not static
class java
{
public int count(int [,] list,int n)
{
int c = 0;
for (int i = 0; i <list.Length; i++)
{
for (int j = 0; j < list.Length; j++)
{
if (list[i, j] == n)
{
c++;
}
}
}
return c;
}
class Program
{
static void Main(string[] args)
{
java jv = new java();
int[,] arr = { { 3, 5, 7, 94 }, {5, 6, 3, 50 } };
int k=0;
jv.count(arr,k);
}
}

Iterating Multi-Dimensional arrays requires you to iterate each dimension with it's own Length, which means i and j should be 0-3 and 0-1 respectively.
as can be seen in the picture but for a different dimensioned array:
GetLength(0) would return 4.
GetLength(1) would return 3.
What you are doing is iterating them when i = (0 to Length) over j = (0 to Length) when Length = Height * Width = 8 in your case which means 8 over 8.
So your count() method should look like that:
public int count(int[,] list,int n)
{
int c = 0;
for (int i = 0; i < list.GetLength(0); i++)
{
for (int j = 0; j < list.GetLength(1); j++)
{
if (list[i, j] == n)
{
c++;
}
}
}
return c;
}
if you would like to iterate the array as an array of arrays instead of getting things complicated with "Which dimension am I iterating now?" you can use Jagged Arrays (Of course there are more things to consider about it), this will allow you to replace the whole method with this one short Linq:
public int count(int[][] list,int n)
{
return list.SelectMany(x => x).Count(x => x == n);
}
or:
public int count(int[][] list, int n)
{
return list.Sum(x => x.Count(y => y == n));
}

Note the i against j in inner for.
And do use i <list.GetLength(0) and j < list.GetLength(1) against list.Length
class java
{
public int count(int [,] list,int n)
{
int c = 0;
for (int i = 0; i < list.GetLength(0); i++)
{
for (int j = 0; j < list.GetLength(1); j++)
{
if (list[i, j] == n)
{
c++;
}
}
}
return c;
}
class Program
{
static void Main(string[] args)
{
java jv = new java();
int[,] arr = { {3,5,7,94 }, {5,6,3,50 } };
int k=5;
Console.WriteLine(jv.count(arr,k));
}
}

Since Array has implemented IEnumerable you can simply use foreach loop here (feel free to change static to instance method) :
public static int count(int[,] list, int n)
{
int c = 0;
foreach (var item in list) if (item == n) c++;
return c;
}
Usage:
static void Main()
{
var r = count(new int[,]{
{
5, 8, 7, 8
},
{
0, 8, 9, 3
}}, 8);
Console.WriteLine(r);
output : 3
P.S.
Generally if possible, it is best to use a for loop as it is faster than foreach but in these case i like that if you use foreach you don't have nested for loops nor GetLength(x) calls it's just one line of code and it has almost same performance...

Your error is in this line:
for (int j = 0; i < list.Length; j++)
It should be
for (int j = 0; j < list.Length; j++)

Related

Change this nested for loop to recursion [duplicate]

This question already has an answer here:
Creating all possible arrays without nested for loops [closed]
(1 answer)
Closed 6 years ago.
I posted this similar, previous question, but I was not very clear.
I have the following code:
int N=4;
int[] myArray = new int[N];
for (int i1 = 1; i1 < N; i1++)
myArray[0]=i1;
for (int i2 = 1; i2 < N; i2++)
myArray[1]=i2;
for (int i3 = 1; i3 < N; i3++)
myArray[2]=i3;
for (int i4 = 1; i4 < N; i4++)
{
myArray[3]=i4;
foreach (var item in myArray)
Console.Write(item.ToString());
Console.Write(Environment.NewLine);
}
This outputs the following:
1111
1112
1113
1121
1122
1123
1131
....
3332
3333
Is there a simple way to change this nested for loop to recursion? I am not very skilled at programming, so the simpler, the better. I am not worried about how efficient the code is.
I, effectively, would like to be able to change the int N in my code to different numbers, without having to add or remove anything from my code.
EDIT
Here is what I have so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sandbox
{
class Program
{
static void Main(string[] args)
{
int class_length = 4;
int[] toric_class = Enumerable.Repeat(1, class_length).ToArray();
Recursion(toric_class, class_length, 1, 3);
Console.Read();
}
static void Recursion(int[] toric_class, int length, int number, int spot)
{
if (number < 4)
{
toric_class[spot] = number;
foreach (var item in toric_class)
{
Console.Write(item.ToString());
}
Console.Write(Environment.NewLine);
Recursion(toric_class, length, number + 1, spot);
}
}
}
}
This only outputs
1111
1112
1113
I am unsure of where to go from here.
public static void Set(int[] array, int index, int N)
{
if (index == N)
{
foreach (var item in array)
Console.Write(item.ToString());
Console.Write(Environment.NewLine);
return;
}
for (int i = 1; i < N; i++)
{
array[index] = i;
Set(array, index + 1, N);
}
}
And call it this way:
int N = 4;
int[] myArray = new int[N];
Set(myArray, 0, N);
If you want just to simplify and generalize the solition, you don't want any recursion:
// N - length of the array
// K - kind of radix; items of the array will be in [1..K] range
private static IEnumerable<int[]> Generator(int N = 4, int K = 3) {
int[] items = Enumerable
.Repeat(1, N)
.ToArray();
do {
yield return items.ToArray(); // .ToArray() : let's return a copy of the array
for (int i = N - 1; i >= 0; --i)
if (items[i] < K) {
items[i] += 1;
break;
}
else
items[i] = 1;
}
while (!items.All(item => item == 1));
}
Test
string test = string.Join(Environment.NewLine, Generator(4)
.Select(items => string.Concat(items)));
Console.Write(test);
Outcome:
1111
1112
1113
1121
1122
...
3321
3322
3323
3331
3332
3333

are there anybody can help me ? i'm writting a program ( reversing an array ), but it doesn't run :(

I'm writing a program about reversing an array with 3 methods (GenerateNumber, reverse and PrintOut).
Unfortunately it doesn't run. Can you help me to find the error and fix them?
Why doesn't it run?
public class Program
{
static int[] GenerateNumber()
{
string a = Console.ReadLine();
int b = Convert.ToInt32(a);
int[] number = new int [b];
string[] c = new string[b];
for (int index = 0; index < number.Length; index++)
{
c[index] = Console.ReadLine();
number [index]= Convert.ToInt32(c[index]);
}
return number;
}
static int[] reverse(int[] array)
{
for (int index =0; index <array.Length; index++)
{
int c = array[index];
array[index] = array[array.Length - index - 1];
array[array.Length - index - 1]= c;
}
return array;
}
static int[] PrintOut (int[] array)
{
for (int index = 0; index > array.Length; index++)
Console.Write(array[index]);
return array;
}
static void Main(string[] args)
{
int[] number = GenerateNumber();
reverse(number);
PrintOut(number);
Console.ReadKey();
}
The immediate cause of the misbehaviour is in the
static int[] PrintOut (int[] array)
{
for (int index = 0; index > array.Length; index++) // <- wrong condition
Console.Write(array[index]);
The comparison should be < instead of >:
for (int index = 0; index < array.Length; index++)
A better choice, however, is foreach loop instead of for
foreach (var item in array)
Console.Write(item); // propably, you want WriteLine not Write
Some suggestions:
public class Program {
static int[] GenerateNumber() {
// You don't want "c" array, but "number"
int[] number = new int [Convert.ToInt32(Console.ReadLine())];
for (int index = 0; index < number.Length; index++)
number [index] = Convert.ToInt32(Console.ReadLine());
return number;
}
// Nice implementation, nothing to improve but naming (reverse -> Reverse)
static int[] Reverse(int[] array) {
for (int index = 0; index <array.Length; index++) {
int c = array[index];
array[index] = array[array.Length - index - 1];
array[array.Length - index - 1] = c;
}
return array;
}
static int[] PrintOut (int[] array) {
// foreach is easier to implement and easier to read
foreach (var item in array)
Console.WriteLine(item); // <- you, probably, want WriteLine not Write
return array;
}
static void Main(string[] args) {
int[] number = GenerateNumber();
Reverse(number);
PrintOut(number);
Console.ReadKey();
}

Gather all possible combinations of 2 from a list

I have a list with 10 items in it. I am trying to output to console every possible pairing of 2. But it cannot pair with itself. For example
1,2
1,3
1,4 etc...
I found this to find all possible combinations within a list. Can someone help me modify it please?
private static void GetCombination(IList list)
{
var count = Math.Pow(2, list.Count);
for (var i = 1; i <= count - 1; i++)
{
var str = Convert.ToString(i, 2).PadLeft(list.Count, '0');
for (var j = 0; j < str.Length; j++)
{
if (str[j] == '1')
{
Console.Write(list[j]);
}
}
Console.WriteLine();
}
}
So if you have a list with 1 to 10, you need 1,2 1,3 1,4...1,10 - 2,1 2,3..2,10 and so on.
You just have to use bubble and check if the first index is different from the second.
For more clarification, here is an example:
List<int> mylist = new List<int>(new int[] { 1,2,3,4,5,6,7,8,9 });
GetCombination(mylist);
private static void GetCombination(IList<int> values)
{
for (int i = 0; i < values.Count; i++)
{
for (int j = 0; j < values.Count; j++)
{
if (i != j)
{
Console.WriteLine(values[i] + " " + values[j]);
}
}
}
}
This is such a easy question.Adding to the answer of #FirstOne
you can also return the List containing all the combinations from the function:
List mylist = new List(new int[] { 1,2,3,4,5,6,7,8,9 });
GetCombination(mylist);
public static IList<Tuple<int,int>> GetCombination(IList<int> values)
{
List<Tuple<int,int>> _temp=new List<Tuple<int, int>>();
for (int i = 0; i < values.Count; i++)
{
for (int j = 0; j < values.Count; j++)
{
if (i != j)
{
_temp.Add(Tuple.Create(i, j));
}
}
}
return _temp;
}

Remove Nulls from string[,]

I have a string array defined in c# as
string[,] options = new string[100,3];
Throughout the code it gets populated with data but not always filled.
So if I have 80 parts of it filled and 20 parts of it not filled. The 20 parts have nulls in them or 60 nulls at the end. Is there an easy way to resize the array so that after filling it the array is the same as
String[,] options = new string[80,3];
It would have to be resized based on the position of the first set of 3 nulls it found.
If this was a jagged array I would have done
options = options.Where(x => x != null).ToArray();
The method is quite long, because it has to check every row twice...
public static string[,] RemoveEmptyRows(string[,] strs)
{
int length1 = strs.GetLength(0);
int length2 = strs.GetLength(1);
// First we count the non-emtpy rows
int nonEmpty = 0;
for (int i = 0; i < length1; i++)
{
for (int j = 0; j < length2; j++)
{
if (strs[i, j] != null)
{
nonEmpty++;
break;
}
}
}
// Then we create an array of the right size
string[,] strs2 = new string[nonEmpty, length2];
for (int i1 = 0, i2 = 0; i2 < nonEmpty; i1++)
{
for (int j = 0; j < length2; j++)
{
if (strs[i1, j] != null)
{
// If the i1 row is not empty, we copy it
for (int k = 0; k < length2; k++)
{
strs2[i2, k] = strs[i1, k];
}
i2++;
break;
}
}
}
return strs2;
}
Use it like:
string[,] options = new string[100, 3];
options[1, 0] = "Foo";
options[3, 1] = "Bar";
options[90, 2] = "fiz";
options = RemoveEmptyRows(options);
As suggested by Alexei, there is another way of doing this:
public static string[,] RemoveEmptyRows2(string[,] strs)
{
int length1 = strs.GetLength(0);
int length2 = strs.GetLength(1);
// First we put somewhere a list of the indexes of the non-emtpy rows
var nonEmpty = new List<int>();
for (int i = 0; i < length1; i++)
{
for (int j = 0; j < length2; j++)
{
if (strs[i, j] != null)
{
nonEmpty.Add(i);
break;
}
}
}
// Then we create an array of the right size
string[,] strs2 = new string[nonEmpty.Count, length2];
// And we copy the rows from strs to strs2, using the nonEmpty
// list of indexes
for (int i1 = 0; i1 < nonEmpty.Count; i1++)
{
int i2 = nonEmpty[i1];
for (int j = 0; j < length2; j++)
{
strs2[i1, j] = strs[i2, j];
}
}
return strs2;
}
This one, in the tradeoff memory vs time, chooses time. It is probably faster, because it doesn't have to check every row twice, but it uses more memory, because it puts somewhere a list of the non-empty indexes.
I went for all rows until you find an row with all null values:
Needs some clean up and will obviously remove non-null rows that occur after the first all null row. The requirement wasn't too clear here
EDIT: Just seen the comment clarifying requirement to remove all null rows - I've tweaked the below to avoid downvotes but a more comprehensive answer is already accepted (and is more efficient) :)
void Main()
{
string[,] options = new string[100,3];
options[0,0] = "bleb";
options[1,1] = "bleb";
options[2,0] = "bleb";
options[2,1] = "bleb";
options[3,2] = "bleb";
options[4,1] = "bleb";
string[,] trimmed = TrimNullRows(options);
Console.WriteLine(trimmed);
}
public string[,] TrimNullRows(string[,] options)
{
IList<string[]> nonNullRows = new List<string[]>();
for (int x = 0; x < options.GetLength(0); x++)
{
bool allNull = true;
var row = new string[options.GetLength(1)];
for (int y = 0; y < options.GetLength(1); y++)
{
row[y] = options[x,y];
allNull &= options[x,y] == null;
}
if (!allNull)
{
nonNullRows.Add(row);
}
}
var optionsTrimmed = new string[nonNullRows.Count, options.GetLength(1)];
for (int i=0;i<nonNullRows.Count;i++)
{
for (int j=0;j<options.GetLength(1);j++)
{
optionsTrimmed[i, j] = nonNullRows[i][j];
}
}
return optionsTrimmed;
}
You can also get yourself some helpers to convert between jagged and multi-dimensional representations. This is pretty silly, of course, but for arrays as small as the ones you're showing (and also, very sparse arrays), it'll be fine.
void Main()
{
string[,] options = new string[100,3];
options[3, 1] = "Hi";
options[5, 0] = "Dan";
var results =
options
.JagIt()
.Where(i => i.Any(j => j != null))
.UnjagIt();
results.Dump();
}
static class Extensions
{
public static IEnumerable<IEnumerable<T>> JagIt<T>(this T[,] array)
{
for (var i = 0; i < array.GetLength(0); i++)
yield return GetRow(array, i);
}
public static IEnumerable<T> GetRow<T>(this T[,] array, int rowIndex)
{
for (var j = 0; j < array.GetLength(1); j++)
yield return array[rowIndex, j];
}
public static T[,] UnjagIt<T>(this IEnumerable<IEnumerable<T>> jagged)
{
var rows = jagged.Count();
if (rows == 0) return new T[0, 0];
var columns = jagged.Max(i => i.Count());
var array = new T[rows, columns];
var row = 0;
var column = 0;
foreach (var r in jagged)
{
column = 0;
foreach (var c in r)
{
array[row, column++] = c;
}
row++;
}
return array;
}
}
The JagIt method is pretty simple of course - we'll just iterate over the rows, and yield the individual items. This gives us an enumerable of enumerables, which we can use in LINQ quite easily. If desired, you could transform those into arrays, of course (say, Select(i => i.ToArray()).ToArray()).
The UnjagIt method is a bit more talkative, because we need to create the target array with the correct dimensions first. And there's no unyield instruction to simplify that :D
This is pretty inefficient, of course, but that isn't necessarily a problem. You could save yourself some of the iterations by keeping the inner enumerable an array, for example - that will save us having to iterate over all the inner items.
I'm mostly keeping this as the memory-cheap, CPU-intensive alternative to #xanatos' memory-intensive, CPU-cheap (relatively).
Of course, the main bonus is that it can be used to treat any multi-dimensional arrays as jagged arrays, and convert them back again. General solutions usually aren't the most efficient :D
Yet another variant with linq
static string[,] RemoveNotNullRow(string[,] o)
{
var rowLen = o.GetLength(1);
var notNullRowIndex = (from oo in o.Cast<string>().Select((x, idx) => new { idx, x })
group oo.x by oo.idx / rowLen into g
where g.Any(f => f != null)
select g.Key).ToArray();
var res = new string[notNullRowIndex.Length, rowLen];
for (int i = 0; i < notNullRowIndex.Length; i++)
{
Array.Copy(o, notNullRowIndex[i] * rowLen, res, i * rowLen, rowLen);
}
return res;
}

How do I 'foreach' through a two-dimensional array?

I've got a two-dimensional array,
string[,] table = {
{ "aa", "aaa" },
{ "bb", "bbb" }
};
And I'd like to foreach through it like this,
foreach (string[] row in table)
{
Console.WriteLine(row[0] + " " + row[1]);
}
But, I get the error:
Can't convert type string to string[]
Is there a way I can achieve what I want, i.e. iterate through the first dimension of the array with the iterator variable returning me the one-dimensional array for that row?
Multidimensional arrays aren't enumerable. Just iterate the good old-fashioned way:
for (int i = 0; i < table.GetLength(0); i++)
{
Console.WriteLine(table[i, 0] + " " + table[i, 1]);
}
As others have suggested, you could use nested for-loops or redeclare your multidimensional array as a jagged one.
However, I think it's worth pointing out that multidimensional arrays are enumerable, just not in the way that you want. For example:
string[,] table = {
{ "aa", "aaa" },
{ "bb", "bbb" }
};
foreach (string s in table)
{
Console.WriteLine(s);
}
/* Output is:
aa
aaa
bb
bbb
*/
If you define your array like this:
string[][] table = new string[][] {
new string[] { "aa", "aaa" },
new string[]{ "bb", "bbb" }
};
Then you can use a foreach loop on it.
UPDATE: I had some time on my hands, so ... I went ahead and fleshed out this idea. See below for the code.
Here's a bit of a crazy answer:
You could do what you're looking for -- essentially treat a two-dimensional array as a table with rows -- by writing a static method (perhaps an extension method) that takes a T[,] and returns an IEnumerable<T[]>. This would require copying each "row" of the underlying table into a new array, though.
A perhaps better (though more involved) approach would be to actually write a class that implements IList<T> as a wrapper around a single "row" of a two-dimensional array (you would probably set IsReadOnly to true and just implement the getter for the this[int] property and probably Count and GetEnumerator; everything else could throw a NotSupportedException). Then your static/extension method could return an IEnumerable<IList<T>> and provide deferred execution.
That way you could write code pretty much like what you have:
foreach (IList<string> row in table.GetRows()) // or something
{
Console.WriteLine(row[0] + " " + row[1]);
}
Just a thought.
Implementation suggestion:
public static class ArrayTableHelper {
public static IEnumerable<IList<T>> GetRows<T>(this T[,] table) {
for (int i = 0; i < table.GetLength(0); ++i)
yield return new ArrayTableRow<T>(table, i);
}
private class ArrayTableRow<T> : IList<T> {
private readonly T[,] _table;
private readonly int _count;
private readonly int _rowIndex;
public ArrayTableRow(T[,] table, int rowIndex) {
if (table == null)
throw new ArgumentNullException("table");
if (rowIndex < 0 || rowIndex >= table.GetLength(0))
throw new ArgumentOutOfRangeException("rowIndex");
_table = table;
_count = _table.GetLength(1);
_rowIndex = rowIndex;
}
// I didn't implement the setter below,
// but you easily COULD (and then set IsReadOnly to false?)
public T this[int index] {
get { return _table[_rowIndex, index]; }
set { throw new NotImplementedException(); }
}
public int Count {
get { return _count; }
}
bool ICollection<T>.IsReadOnly {
get { return true; }
}
public IEnumerator<T> GetEnumerator() {
for (int i = 0; i < _count; ++i)
yield return this[i];
}
// omitted remaining IList<T> members for brevity;
// you actually could implement IndexOf, Contains, etc.
// quite easily, though
}
}
...now I think I should give StackOverflow a break for the rest of the day ;)
It depends on how you define your multi-dimensional array. Here are two options:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
// First
string[,] arr1 = {
{ "aa", "aaa" },
{ "bb", "bbb" }
};
// Second
string[][] arr2 = new[] {
new[] { "aa", "aaa" },
new[] { "bb", "bbb" }
};
// Iterate through first
for (int x = 0; x <= arr1.GetUpperBound(0); x++)
for (int y = 0; y <= arr1.GetUpperBound(1); y++)
Console.Write(arr1[x, y] + "; ");
Console.WriteLine(Environment.NewLine);
// Iterate through second second
foreach (string[] entry in arr2)
foreach (string element in entry)
Console.Write(element + "; ");
Console.WriteLine(Environment.NewLine);
Console.WriteLine("Press any key to finish");
Console.ReadKey();
}
}
}
Here's a simple extension method that returns each row as an IEnumerable<T>. This has the advantage of not using any extra memory:
public static class Array2dExt
{
public static IEnumerable<IEnumerable<T>> Rows<T>(this T[,] array)
{
for (int r = array.GetLowerBound(0); r <= array.GetUpperBound(0); ++r)
yield return row(array, r);
}
static IEnumerable<T> row<T>(T[,] array, int r)
{
for (int c = array.GetLowerBound(1); c <= array.GetUpperBound(1); ++c)
yield return array[r, c];
}
}
Sample usage:
static void Main()
{
string[,] siblings = { { "Mike", "Amy" }, { "Mary", "Albert" }, {"Fred", "Harry"} };
foreach (var row in siblings.Rows())
Console.WriteLine("{" + string.Join(", ", row) + "}");
}
string[][] table = { ... };
string[][] languages = new string[2][];
languages[0] = new string[2];
languages[1] = new string[3];
// inserting data into double dimensional arrays.
for (int i = 0; i < 2; i++)
{
languages[0][i] = "Jagged"+i.ToString();
}
for (int j = 0; j < 3; j++)
{
languages[1][j] = "Jag"+j.ToString();
}
// doing foreach through 2 dimensional arrays.
foreach (string[] s in languages)
{
foreach (string a in s)
{
Console.WriteLine(a);
}
}
Using LINQ you can do it like this:
var table_enum = table
// Convert to IEnumerable<string>
.OfType<string>()
// Create anonymous type where Index1 and Index2
// reflect the indices of the 2-dim. array
.Select((_string, _index) => new {
Index1 = (_index / 2),
Index2 = (_index % 2), // ← I added this only for completeness
Value = _string
})
// Group by Index1, which generates IEnmurable<string> for all Index1 values
.GroupBy(v => v.Index1)
// Convert all Groups of anonymous type to String-Arrays
.Select(group => group.Select(v => v.Value).ToArray());
// Now you can use the foreach-Loop as you planned
foreach(string[] str_arr in table_enum) {
// …
}
This way it is also possible to use the foreach for looping through the columns instead of the rows by using Index2 in the GroupBy instead of Index 1. If you don't know the dimension of your array then you have to use the GetLength() method to determine the dimension and use that value in the quotient.
I'm not a big fan of this method because of the memory usage involved, but if you use the arrays it produces, it isn't such a waste.
public static void ForEachRow<T>(this T[,] list, Action<int, T[]> action)
{
var len = list.GetLength(0);
var sub = list.GetLength(1);
T[] e;
int i, j;
for (i = 0; i < len; i++)
{
e = new T[sub];
for (j = 0; j < sub; j++)
{
e[j] = list[i, j];
}
action(i, e);
}
}
Implementation:
var list = new[,]{0x0, 0x1, 0x2, 0x4, 0x8};
list.ForEachRow((i, row) =>
{
for (var j = 0; j < row.Length; j++)
{
Console.WriteLine("[{0},{1}]: {2}", i, j, row[j]);
}
});
The other solution I found is less memory intensive, but will use more CPU, especially when the dimensions of the arrays' entries are larger.
public static void ForEachRow<T>(this T[,] list, Action<int, IEnumerable<T>> action)
{
var len = list.GetLength(0);
var sub = list.GetLength(1);
int i, j;
IEnumerable<T> e;
for (i = 0; i < len; i++)
{
e = Enumerable.Empty<T>();
for (j = 0; j < sub; j++)
{
e = e.Concat(AsEnumerable(list[i, j]));
}
action(i, e);
}
}
private static IEnumerable<T> AsEnumerable<T>(T add)
{
yield return add;
}
Implementation:
var list = new[,]{0x0, 0x1, 0x2, 0x4, 0x8};
list.ForEachRow((i, row) =>
{
var j = 0;
forrach (var o in row)
{
Console.WriteLine("[{0},{1}]: {2}", i, j, o);
++j;
}
});
As a whole, I find the first option to be more intuitive, especially if you want to access the produced array by its indexer.
At the end of the day, this is all just eye candy, neither methods should really be used in favour of directly accessing the source array;
for (var i = 0; i < list.GetLength(0); i++)
{
foreach (var j = 0; j < list.GetLength(1); j++)
{
Console.WriteLine("[{0},{1}]: {2}", i, j, list[i, j]);
}
}
Remember that a multi-dimensional array is like a table. You don't have an x element and a y element for each entry; you have a string at (for instance) table[1,2].
So, each entry is still only one string (in your example), it's just an entry at a specific x/y value. So, to get both entries at table[1, x], you'd do a nested for loop. Something like the following (not tested, but should be close)
for (int x = 0; x < table.Length; x++)
{
for (int y = 0; y < table.Length; y += 2)
{
Console.WriteLine("{0} {1}", table[x, y], table[x, y + 1]);
}
}
I try this. I hope to help. It work with
static void Main()
{
string[,] matrix = {
{ "aa", "aaa" },
{ "bb", "bbb" }
};
int index = 0;
foreach (string element in matrix)
{
if (index < matrix.GetLength(1))
{
Console.Write(element);
if (index < (matrix.GetLength(1) - 1))
{
Console.Write(" ");
}
index++;
}
if (index == matrix.GetLength(1))
{
Console.Write("\n");
index = 0;
}
}

Categories

Resources