Question

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...

SELECT smID, MIN(entID) FROM table
WHERE exID = :exID
AND smID IN (1,2,3,4,5,6,7,8, etc)
GROUP BY smID 

The code I have so far is as follows...

DataTable dt = ds.Tables["myTable"];

var query =
    from g in dt.AsEnumerable()
    where g.Field<string>("exID") == exID
    && smIDs.Contains(g.Field<string>("smID"))
    group g by g.Field<string>("smID") into rowGroup
    select new
    {
        smID = rowGroup.Key,
        minEntID = rowGroup.Min(g => g.Field<int>("entID"))
    };

exID is a string variable in the method and smIDs 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...

             if (query.Count() > 0)
             {
                 foreach (var item in query)
                 {
                     string s = item.smID;
                     int i = (int)item.minEntID;
                 }
             }

I have been unable to figure out what I am doing wrong.

VS points to...

minEntID = rowGroup.Min(g => g.Field<int>("entID"))

This is the first two lines of the stack trace...

   at System.Data.DataRowExtensions.UnboxT`1.ValueField(Object value)
   at System.Data.DataRowExtensions.Field[T](DataRow row, String columnName)

Any pointers would be most appreciated. Thanks.

Était-ce utile?

La solution

Judging by the exception and stack trace, the type you're specifying for the endID field in your query doesn't match the DataType for that column in the DataTable. These must match -- you cannot use the Field method to cast the value to a different type.

Autres conseils

I used Linqer to come up with this code:

from t in db.Table // your C# table / collection here, of course
where t.ExId == stackoverflow.ExId 
    && (new int[] {1, 2, 3 }).Contains(t.SmId)
group t by new { t.SmId } into g
select new {
   SmId = g.Key.SmId,
   minEntID = g.Min(p => p.EntId)
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top