[英]How can I add to an existing array/ienumerable collection in a foreach loop
[英]How can I implement IEnumerable<T> on a collection that has a MultiDimensional Array inner list?
我有一個收藏:
interface IPinCollection : IEnumerable<IPin>
{
IPin this[int [,] indices] { get; set; }
}
基本上,它有一個內部列表作為矩陣,每個 [rowindex,columnIndex] 中都有 IPin 實例。
我想要實現的是能夠使用 for..each 遍歷該矩陣的所有 IPin 實例。
你能建議我一種線程安全、簡單和快速的方法來實現 IEnumerable 來實現這一點嗎?
如果您的基礎屬性是Array
,則可以使用Array.GetLength(int dimension)
來獲取指定維度中數組的長度,盡管在這種情況下您可以簡單地使用其內置枚舉器。
這有效,例如:
int[,] arr = new int[,]
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 },
{ 10, 11, 12 }
};
foreach (int i in arr)
Console.WriteLine(i);
這意味着您可以簡單地從數組中返回值,按照其枚舉器返回它們的順序:
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
}
如果數組是已知維度的,例如private readonly IPin[,] data;
,然后實際上非常簡單(因為您已經可以在多維數組上進行foreach
;但請注意, T[*,*]
本身並不實現IEnumerable<T>
- 因為這在技術上不是foreach
的要求):
public IEnumerator<IPin> GetEnumerator()
{
foreach (IPin pin in pins) yield return pin;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.