title: c# LINQ to dataset IN clause contains, group, min
body: <p>I am new to LINQ but am trying to tackle a tough one right off the bat.  I am trying to do LINQ to dataset and emulate the following query...</p>
  
  <pre><code>SELECT smID, MIN(entID) FROM table
  WHERE exID = :exID
  AND smID IN (1,2,3,4,5,6,7,8, etc)
  GROUP BY smID 
  </code></pre>
  
  <p>The code I have so far is as follows...</p>
  
  <pre><code>DataTable dt = ds.Tables["myTable"];
  
  var query =
      from g in dt.AsEnumerable()
      where g.Field&lt;string&gt;("exID") == exID
      &amp;&amp; smIDs.Contains(g.Field&lt;string&gt;("smID"))
      group g by g.Field&lt;string&gt;("smID") into rowGroup
      select new
      {
          smID = rowGroup.Key,
          minEntID = rowGroup.Min(g =&gt; g.Field&lt;int&gt;("entID"))
      };
  </code></pre>
  
  <p><strong>exID</strong> is a string variable in the method and <strong>smIDs</strong> is a List of strings also created earlier in the method.  I created the following code to try and see my results and it throws an "System.InvalidCastException" error at query.Count...</p>
  
  <pre><code>             if (query.Count() &gt; 0)
               {
                   foreach (var item in query)
                   {
                       string s = item.smID;
                       int i = (int)item.minEntID;
                   }
               }
  </code></pre>
  
  <p>I have been unable to figure out what I am doing wrong.  </p>
  
  <p>VS points to...</p>
  
  <pre><code>minEntID = rowGroup.Min(g =&gt; g.Field&lt;int&gt;("entID"))
  </code></pre>
  
  <p>This is the first two lines of the stack trace...</p>
  
  <pre><code>   at System.Data.DataRowExtensions.UnboxT`1.ValueField(Object value)
     at System.Data.DataRowExtensions.Field[T](DataRow row, String columnName)
  </code></pre>
  
  <p>Any pointers would be most appreciated.  Thanks.</p>