Posted By

joelsand on 05/17/11


Tagged

indexof Linq indexwhere


Versions (?)

LINQ Index of item - IndexWhere()


 / Published in: C#
 

Find the index of an item in a collection with a simple statement. For example:

int index = myList.IndexWhere(item => item.Something == someOtherThing);

  1. /*** Source code ***/
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Collections;
  7.  
  8. namespace Snippets
  9. {
  10. public static class IEnumerableExtensions
  11. {
  12. /// <summary>
  13. /// Finds the index in the collection where the predicate evaluates to true.
  14. ///
  15. /// Returns -1 if no matching item found
  16. /// </summary>
  17. /// <typeparam name="TSource">Type of collection</typeparam>
  18. /// <param name="source">Source collection</param>
  19. /// <param name="predicate">Function to evaluate</param>
  20. /// <returns>Index where predicate is true, or -1 if not found.</returns>
  21. public static int IndexWhere<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
  22. {
  23. var enumerator = source.GetEnumerator();
  24. int index = 0;
  25. while (enumerator.MoveNext())
  26. {
  27. TSource obj = enumerator.Current;
  28. if (predicate(obj))
  29. return index;
  30. index++;
  31. }
  32. return -1;
  33. }
  34.  
  35. /// <summary>
  36. /// Finds the index in the collection where the predicate evaluates to true.
  37. ///
  38. /// Returns -1 if no matching item found
  39. /// </summary>
  40. /// <typeparam name="TSource">Type of collection</typeparam>
  41. /// <param name="source">Source collection</param>
  42. /// <param name="predicate">Function to evaluate</param>
  43. /// <returns>Index where predicate is true, or -1 if not found.</returns>
  44. public static int IndexWhere<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate)
  45. {
  46. var enumerator = source.GetEnumerator();
  47. int index = 0;
  48. while (enumerator.MoveNext())
  49. {
  50. TSource obj = enumerator.Current;
  51. if (predicate(obj, index))
  52. return index;
  53. index++;
  54. }
  55. return -1;
  56. }
  57. }
  58. }
  59.  
  60. /*** Unit Tests ***/
  61. using ProtectedTrust.Common;
  62. using Microsoft.VisualStudio.TestTools.UnitTesting;
  63. using System;
  64. using System.Collections.Generic;
  65.  
  66. namespace SnippetsTests
  67. {
  68.  
  69.  
  70. /// <summary>
  71. ///This is a test class for IEnumerableExtensionsTest and is intended
  72. ///to contain all IEnumerableExtensionsTest Unit Tests
  73. ///</summary>
  74. [TestClass()]
  75. public class IEnumerableExtensionsTest
  76. {
  77.  
  78.  
  79. private TestContext testContextInstance;
  80.  
  81. /// <summary>
  82. ///Gets or sets the test context which provides
  83. ///information about and functionality for the current test run.
  84. ///</summary>
  85. public TestContext TestContext
  86. {
  87. get
  88. {
  89. return testContextInstance;
  90. }
  91. set
  92. {
  93. testContextInstance = value;
  94. }
  95. }
  96.  
  97. #region Additional test attributes
  98. //
  99. //You can use the following additional attributes as you write your tests:
  100. //
  101. //Use ClassInitialize to run code before running the first test in the class
  102. //[ClassInitialize()]
  103. //public static void MyClassInitialize(TestContext testContext)
  104. //{
  105. //}
  106. //
  107. //Use ClassCleanup to run code after all tests in a class have run
  108. //[ClassCleanup()]
  109. //public static void MyClassCleanup()
  110. //{
  111. //}
  112. //
  113. //Use TestInitialize to run code before running each test
  114. //[TestInitialize()]
  115. //public void MyTestInitialize()
  116. //{
  117. //}
  118. //
  119. //Use TestCleanup to run code after each test has run
  120. //[TestCleanup()]
  121. //public void MyTestCleanup()
  122. //{
  123. //}
  124. //
  125. #endregion
  126.  
  127.  
  128. /// <summary>
  129. ///A test for IndexWhere
  130. ///</summary>
  131. public void IndexWhereTestHelper<TSource>()
  132. {
  133. IEnumerable<TSource> source = null; // TODO: Initialize to an appropriate value
  134. Func<TSource, int, bool> predicate = null; // TODO: Initialize to an appropriate value
  135. int expected = 0; // TODO: Initialize to an appropriate value
  136. int actual;
  137. actual = IEnumerableExtensions.IndexWhere<TSource>(source, predicate);
  138. Assert.AreEqual(expected, actual);
  139. Assert.Inconclusive("Verify the correctness of this test method.");
  140. }
  141.  
  142. [TestMethod()]
  143. public void IndexWhereTest()
  144. {
  145. // create list of numbers
  146. List<int> list = new List<int>();
  147. for (int i = 0; i < 100; i++)
  148. {
  149. list.Add(i);
  150. }
  151.  
  152. // test method with various inputs
  153. int actual = list.IndexWhere((n) => n == 5);
  154. Assert.AreEqual(5, actual);
  155.  
  156. actual = list.IndexWhere((n) => n == 99);
  157. Assert.AreEqual(99, actual);
  158.  
  159. actual = list.IndexWhere((n) => n == 0);
  160. Assert.AreEqual(0, actual);
  161.  
  162. actual = list.IndexWhere((n) => n == 1);
  163. Assert.AreEqual(1, actual);
  164.  
  165. // check one not found
  166. actual = list.IndexWhere((n) => n == 23423);
  167. Assert.AreEqual(-1, actual);
  168. }
  169.  
  170.  
  171.  
  172. [TestMethod()]
  173. public void IndexWhereTest1()
  174. {
  175. // create list of numbers
  176. List<int> list = new List<int>();
  177. for (int i = 0; i < 100; i++)
  178. {
  179. list.Add(i);
  180. }
  181.  
  182. // test method with various inputs
  183. int actual = list.IndexWhere((n, actualRunningIndex) => n == 5);
  184. Assert.AreEqual(5, actual);
  185.  
  186. actual = list.IndexWhere((n, actualRunningIndex) => n == 99);
  187. Assert.AreEqual(99, actual);
  188.  
  189. actual = list.IndexWhere((n, actualRunningIndex) => n == 0);
  190. Assert.AreEqual(0, actual);
  191.  
  192. actual = list.IndexWhere((n, actualRunningIndex) => n == 1);
  193. Assert.AreEqual(1, actual);
  194.  
  195. // check one not found
  196. actual = list.IndexWhere((n, actualRunningIndex) => n == 23423);
  197. Assert.AreEqual(-1, actual);
  198. }
  199.  
  200. [TestMethod()]
  201. public void IndexWhereTestRunningIndex()
  202. {
  203. // create list of numbers
  204. List<int> list = new List<int>();
  205. for (int i = 0; i < 100; i++)
  206. {
  207. list.Add(i);
  208. }
  209.  
  210. int expectedRunningIndex = 0;
  211. list.IndexWhere((n, actualRunningIndex) => AssertRunningIndex(expectedRunningIndex++, actualRunningIndex));
  212. }
  213.  
  214. private static bool AssertRunningIndex(int expectedRunningIndex, int actualRunningIndex)
  215. {
  216. Assert.AreEqual(expectedRunningIndex, actualRunningIndex, "Index passed in predicate method is incorrect.");
  217.  
  218. // always return false so the loop doesn't stop
  219. return false;
  220. }
  221. }
  222. }

Report this snippet  

You need to login to post a comment.