title: C# - Linq optimize code with List and Where clause
body: <p>I have a following code: </p>
  
  <pre><code>        var tempResults = new Dictionary&lt;Record, List&lt;Record&gt;&gt;();            
          errors = new List&lt;Record&gt;();
          foreach (Record record in diag)
          {
              var code = Convert.ToInt16(Regex.Split(record.Line, @"\s{1,}")[4], 16);                
              var cond = codes.Where(x =&gt; x.Value == code &amp;&amp; x.Active).FirstOrDefault();
              if (cond == null)
              {
                  errors.Add(record);
                  continue;
              }
  
              var min = record.Datetime.AddSeconds(downDiff);
              var max = record.Datetime.AddSeconds(upDiff);
  
              //PROBLEM PART - It takes around 4,5ms
              var possibleResults = cas.Where(x =&gt; x.Datetime &gt;= min &amp;&amp; x.Datetime &lt;= max).ToList();
  
              if (possibleResults.Count == 0)
                  errors.Add(record);
              else
              {                    
                  if (!CompareCond(record, possibleResults, cond, ref tempResults, false))
                  {                        
                          errors.Add(record);
                  }
              }
          }
  </code></pre>
  
  <p>variable diag is List of Record</p>
  
  <p>variable cas is List of Record with around 50k items.</p>
  
  <p>The problem is that it's too slowly. The part with the first where clause needs around 4,6599ms, e.g. for 3000 records in List diag it makes 3000*4,6599 = 14 seconds. Is there any option to optimize the code? </p>