简体   繁体   中英

How can I implement IEnumerable<T> on a collection that has a MultiDimensional Array inner list?

I have a collection:

interface IPinCollection : IEnumerable<IPin>
{
 IPin this[int [,] indices] { get; set; }
}

Basically it has an innerlist as matrix which has IPin instance in its each [rowindex,columnIndex].

What I want to achieve is to be able to walkthrough the all IPin instances of this matrix with for..each.

Can you suggest me a thread-safe,simple and quick way to implement IEnumerable to achieve this?

If your underlying property is an Array , you can use Array.GetLength(int dimension) to get the length of the array in the specified dimension, although in that case you can simply use its built-in enumerator.

This works, for example:

int[,] arr = new int[,] 
{ 
   { 1, 2, 3 },    
   { 4, 5, 6 },
   { 7, 8, 9 },
   { 10, 11, 12 } 
};

foreach (int i in arr)
   Console.WriteLine(i);

It means you can simply return values from the array, in the order its enumerator returns them:

class PinCollection : IPinCollection
{
     private IPin[,] _array;

     #region IEnumerable<int> Members

     public IEnumerator<int> GetEnumerator()
     {
         foreach (IPin i in _array)
             yield return i;
     }

     #endregion

     #region IEnumerable Members

     System.Collections.IEnumerator
         System.Collections.IEnumerable.GetEnumerator()
     {
         foreach (IPin i in _array)
             yield return i;
     }

     #endregion

}

If the array is of known dimension, for example private readonly IPin[,] data; , then actually pretty simply (since you can already foreach over a multi-dimensional array; but note that T[*,*] doesn't itself implement IEnumerable<T> - since that isn't technically a requirement for foreach ):

    public IEnumerator<IPin> GetEnumerator()
    {
        foreach (IPin pin in pins) yield return pin;
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

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