簡體   English   中英

如何通過二維數組“foreach”?

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

我有一個二維數組,

string[,] table = {
                       { "aa", "aaa" },
                       { "bb", "bbb" }
                   };

我想像這樣foreach它,

foreach (string[] row in table)
{
    Console.WriteLine(row[0] + " " + row[1]);
}

但是,我收到錯誤:

無法將類型字符串轉換為字符串[]

有沒有辦法可以實現我想要的,即迭代數組的第一維,迭代器變量返回該行的一維數組?

多維數組不可枚舉。 只需迭代好的老式方法:

for (int i = 0; i < table.GetLength(0); i++)
{
    Console.WriteLine(table[i, 0] + " " + table[i, 1]);
}

正如其他人所建議的那樣,您可以使用嵌套的 for 循環或將多維數組重新聲明為鋸齒狀數組。

但是,我認為值得指出的是多維數組可枚舉的,只是不是您想要的方式。 例如:

string[,] table = {
                      { "aa", "aaa" },
                      { "bb", "bbb" }
                  };

foreach (string s in table)
{
    Console.WriteLine(s);
}

/* Output is:
  aa
  aaa
  bb
  bbb
*/

如果您像這樣定義數組:

string[][] table = new string[][] {
                       new string[] { "aa", "aaa" },
                       new string[]{ "bb", "bbb" }
};

然后您可以在其上使用 foreach 循環。

更新:我有一些時間在我的手上,所以......我繼續充實了這個想法。 請參閱下面的代碼。


這是一個有點瘋狂的答案:

可以做你正在尋找的東西——本質上把一個二維數組當作一個帶有行的表——通過編寫一個靜態方法(可能是一個擴展方法),它接受一個T[,]並返回一個IEnumerable<T[]> 不過,這需要將基礎表的每一“行”復制到一個新數組中。

一種可能更好(雖然更復雜)的方法是實際編寫一個實現IList<T>作為二維數組的單個“行”的包裝器(您可能將IsReadOnly設置為 true 並只實現 getter對於this[int]屬性,可能還有CountGetEnumerator ;其他一切都可能拋出NotSupportedException )。 然后您的靜態/擴展方法可以返回一個IEnumerable<IList<T>>並提供延遲執行。

這樣你就可以像你所擁有的那樣編寫代碼:

foreach (IList<string> row in table.GetRows()) // or something
{
    Console.WriteLine(row[0] + " " + row[1]);
}

只是一個想法。


實施建議:

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
    }
}

...現在我想我應該讓 StackOverflow 休息一整天;)

這取決於您如何定義多維數組。 這里有兩個選項:

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();
        }
    }
}

這是一個簡單的擴展方法,它將每一行作為IEnumerable<T> 這具有不使用任何額外內存的優點:

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];
    }
}

示例用法:

static void Main()
{
    string[,] siblings = { { "Mike", "Amy" }, { "Mary", "Albert" }, {"Fred", "Harry"} };

    foreach (var row in siblings.Rows())
        Console.WriteLine("{" + string.Join(", ", row) + "}");
}
string[][] table = { ... };

使用 LINQ,您可以這樣做:

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) {
    // …
}

通過這種方式,也可以使用 foreach 循環遍歷列而不是行,方法是在 GroupBy 中使用 Index2 而不是 Index 1。如果您不知道數組的維度,則必須使用 GetLength()方法來確定維度並在商中使用該值。

由於涉及內存使用,我不是這種方法的忠實擁護者,但是如果您使用它生成的數組,則不會如此浪費。

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);
    }
}

執行:

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]);
    }
});

我發現的另一個解決方案是內存密集度較低,但會使用更多的 CPU,尤其是當數組條目的維度較大時。

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;
}

執行:

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;
    }
});

總的來說,我發現第一個選項更直觀,特別是如果您想通過其索引器訪問生成的數組。

歸根結底,這只是眼花繚亂,這兩種方法都不應該用於直接訪問源數組;

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]);
    }
}

請記住,多維數組就像一張表格。 element and a element for each entry;每個條目都沒有元素和元素; 您在(例如) table[1,2]處有一個字符串。

因此,每個條目仍然只是一個字符串(在您的示例中),它只是特定 x/y 值的條目。 因此,要獲取table[1, x]兩個條目,您需要執行嵌套的 for 循環。 類似於以下內容(未測試,但應該接近)

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]);
    }
}
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);
                }
            }

我試試這個。 我希望有所幫助。 它與

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;
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM