title: Find items that are similar amongst them in List in C# with nested For loops and Linq
body: <p>I have the below code working fine, which finds items which are similar amongst each other within the list by ± 2. I would like to have 2 versions to check which one runs faster.</p>
  
  <p><strong>Version a)</strong> is with nested For Loops, as the code below. However the last part of the code has a !List.Contains() which I would like it to be replaced by another For loop as the Contains() adds 4500 ticks, whereas the other 2 nested for loops only take 1500 ticks. So I would appreciate if someone can help replace the Contains() with another for loop and deliver the same result.</p>
  
  <p><strong>Version b)</strong> the same but with LINQ. </p>
  
  <p><strong>In both versions the items within the output List intTestResult must be: (1, 2, 8, 9, 10, 12)</strong></p>
  
  <pre><code>        int intOffset = 2;
          List&lt;int&gt; intTest = new List&lt;int&gt; { 1, 2, 5, 8, 9, 10, 12, 15, 19, 24 };
          List&lt;int&gt; intTestResult = new List&lt;int&gt;();
  
          var S1 = Stopwatch.StartNew();
  
          for (int a = 0; a &lt; intTest.Count; a++)
  
              {
                  int int1 = intTest[a];
  
                  for (int b = 0; b &lt; intTest.Count; b++)
  
                  {
  
                  int int2 = intTest[b];
  
                  if (int1 + intOffset &gt;= int2 &amp;&amp; int1 - intOffset &lt;= int2 &amp;&amp; int1 != int2)
  
  
                      {
  
                      if (!intTestResult.Contains(int1))                      
  
                          intTestResult.Add(int1);
  
                      }
                  }
              }
  
          S1.Stop();
  
          Console.WriteLine("Ticks = " + S1.ElapsedTicks);                    
  </code></pre>
  
  <p>/* Ticks elapsed 6000</p>
  
  <p>intTestResult items are (1, 2, 8, 9, 10, 12) */</p>