From b0a4a23d81538d1db2839e565fc6df691a1e6761 Mon Sep 17 00:00:00 2001 From: Marcus Cuda Date: Mon, 21 Dec 2009 20:45:12 +0800 Subject: [PATCH] vector: added GetIndexedEnumerator --- src/Numerics/LinearAlgebra/Double/Vector.cs | 17 ++++++++++++++++- .../LinearAlgebraTests/Double/VectorTests.cs | 12 +++++++++++- 2 files changed, 27 insertions(+), 2 deletions(-) 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);