diff --git a/src/Numerics/LinearAlgebra/Double/Vector.cs b/src/Numerics/LinearAlgebra/Double/Vector.cs index 881a116a..82de26ca 100644 --- a/src/Numerics/LinearAlgebra/Double/Vector.cs +++ b/src/Numerics/LinearAlgebra/Double/Vector.cs @@ -837,7 +837,22 @@ namespace MathNet.Numerics.LinearAlgebra.Double } #endregion - + /// + /// Returns an that contains the position and value of the element. + /// + /// An over this vector that contains the position and value of each + /// non-zero element. + /// The enumerator returns a with the key being the element index and the value + /// being the value of the element at that index. For sparse vectors, the enumerator will exclude all elements + /// with a zero value. + public virtual IEnumerable> GetIndexedEnumerator() + { + for (int i = 0; i < Count; i++) + { + yield return new KeyValuePair(i, this[i]); + } + } + #region IEquatable /// diff --git a/src/UnitTests/LinearAlgebraTests/Double/VectorTests.cs b/src/UnitTests/LinearAlgebraTests/Double/VectorTests.cs index 46b99852..8cb09f38 100644 --- a/src/UnitTests/LinearAlgebraTests/Double/VectorTests.cs +++ b/src/UnitTests/LinearAlgebraTests/Double/VectorTests.cs @@ -150,7 +150,17 @@ namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Double var vector = CreateVector(new double[] { 1, 2, 3, 4 }); Assert.AreEqual(2145910784, vector.GetHashCode()); } - + + [Test] + public void GetIndexedEnumerator() + { + Vector vector = CreateVector(_data); + foreach (KeyValuePair pair in vector.GetIndexedEnumerator()) + { + Assert.AreEqual(_data[pair.Key], pair.Value); + } + } + protected abstract Vector CreateVector(int size); protected abstract Vector CreateVector(IList data);