使用 DataTable.Select(somestring) 与 DataTable.AsEnumerable().Where 时出现问题
我正在尝试将首先准备 where 子句并在 DataTable 上调用 select 的旧代码转换为使用 AsEnumerable() 的链接方法。但我的代码不会产生相同的结果。任何见解将不胜感激。
旧代码 - 正在创建一个 where 子句来查找结果
bool OLD_Method()
{
GetNames(inputparam, out DataSet names);
string find = "Name IN ('ABC', 'BCD') AND IsTrue = 1 ";
DataRow[] foundRows = names.Tables[0].Select(find);
if (foundRows.Any()) return true;
return false;
}
新代码接受字符串数组并使用链接方法
bool NEW_Method(string[] params) //NEW_Method(new string[]{'ABC', 'BCD'})
{
GetNames(inputparam, out DataSet names);
var foundRows = names?.Tables[0]?.AsEnumerable()
.Where(myRow => params.Any(p => myRow.Field<string>("Name").Equals(p))
&& myRow.Field<int>("IsTrue") == 1
);
if (foundRows.Any()) return true;
return false;
}
Update - 1 - 如果我只使用一个项目,但使用多个项目,则上述代码有效它正在失败。我认为 Any() 的使用应该充当 OR,但也许我错了。
I am trying to convert an old code which is preparing a where clause first and call select on DataTable, to a chaining method using AsEnumerable(). But my code does not produce the same result. Any insight would be appreciated .
Old Code - which is creating a where clause to find the result
bool OLD_Method()
{
GetNames(inputparam, out DataSet names);
string find = "Name IN ('ABC', 'BCD') AND IsTrue = 1 ";
DataRow[] foundRows = names.Tables[0].Select(find);
if (foundRows.Any()) return true;
return false;
}
New Code which accepts array of strings and uses chaining method
bool NEW_Method(string[] params) //NEW_Method(new string[]{'ABC', 'BCD'})
{
GetNames(inputparam, out DataSet names);
var foundRows = names?.Tables[0]?.AsEnumerable()
.Where(myRow => params.Any(p => myRow.Field<string>("Name").Equals(p))
&& myRow.Field<int>("IsTrue") == 1
);
if (foundRows.Any()) return true;
return false;
}
Update - 1 - Above works, if I were to just use one item, but with multiple it is failing. I thought usage of Any() should act as an OR, but maybe I am wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
旧代码可能执行不区分大小写的比较,而新方法则区分大小写。
实际上,DataTable 上有一个属性可以确定 Select 是否区分大小写。
您可以将第二个查询修改为与第一个查询相同,如下所示。
The old code could be performing a case-insensitive comparison whereas the new method is case sensitive.
There is actually a property on the DataTable that determines whether the Select will be case-sensitive or not.
You can amend your second query to be the same as the first as follows.