时间:2019-03-17 标签:c#LINQ to dataset IN Clause contains,group,min
我是 LINQ 的新手,但我正在尝试立即解决一个棘手的问题。我正在尝试对数据集执行 LINQ 并模拟以下查询...
SELECT smID, MIN(entID) FROM table
WHERE exID = :exID
AND smID IN (1,2,3,4,5,6,7,8, etc)
GROUP BY smID
到目前为止我的代码如下...
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 是方法中的字符串变量,smIDs 是也在该方法之前创建的字符串列表。我创建了以下代码来尝试查看我的结果,它在 query.Count 处抛出“System.InvalidCastException”错误...
if (query.Count() > 0)
{
foreach (var item in query)
{
string s = item.smID;
int i = (int)item.minEntID;
}
}
我一直无法弄清楚我做错了什么。
VS 指向...
minEntID = rowGroup.Min(g => g.Field<int>("entID"))
这是堆栈跟踪的前两行...
at System.Data.DataRowExtensions.UnboxT`1.ValueField(Object value)
at System.Data.DataRowExtensions.Field[T](DataRow row, String columnName)
任何指针将不胜感激。谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据异常和堆栈跟踪判断,您为查询中的 endID 字段指定的类型与 DataTable 中该列的 DataType 不匹配。它们必须匹配——您不能使用 Field 方法将值转换为不同的类型。
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.
我使用 Linqer 得出以下代码:
I used Linqer to come up with this code: