title: Slow LINQ Performance on DataTable Where Clause?
body: <p>I'm dumping a table out of MySQL into a DataTable object using MySqlDataAdapter. Database input and output is doing fine, but my application code seems to have a performance issue I was able to track down to a specific LINQ statement.</p>
  
  <p>The goal is simple, search the contents of the DataTable for a column value matching a specific string, just like a traditional <code>WHERE column = 'text'</code> SQL clause.</p>
  
  <p>Simplified code:</p>
  
  <pre><code>foreach (String someValue in someList) {
      String searchCode = OutOfScopeFunction(someValue);
      var results = emoteTable.AsEnumerable()
          .Where(myRow =&gt; myRow.Field&lt;String&gt;("code") == searchCode)
          .Take(1);
      if (results.Any()) {
          results.First()["columnname"] = 10;
      }
  }
  </code></pre>
  
  <p>This simplified code is executed thousands of times, once for each entry in <code>someList</code>. When I run Visual Studio Performance Profiler I see that the "<code>results.Any()</code>" line is highlighted as consuming 93.5% of the execution time.</p>
  
  <p>I've tried several different methods for optimizing this code, but none have improved performance while keeping the <code>emoteTable</code> DataTable as the primary source of the data. I can convert <code>emoteTable</code> to <code>Dictionary&lt;String, DataRow&gt;</code> outside of the foreach, but then I have to keep the DataTable and the Dictionary in sync, which while still a performance improvement, feels wrong.</p>
  
  <p>Three questions:</p>
  
  <ol>
  <li>Is this the proper way to search for a value in a DataTable (equivalent of a traditional SQL WHERE clause)? If not, how SHOULD it be done?</li>
  <li>Addendum to 1, regardless of the proper way, what is the fastest (execution time)?</li>
  <li>Why does the <code>results.Any()</code> line consume 90%+ resources? In this situation it makes more sense that the <code>var results</code> line should consume the resources, after all, it's the line doing the actual search, right?</li>
  </ol>
  
  <p>Thank you for your time. If I find an answer I shall post it here as well.</p>