应用程序中,提高筛选数据表中行的性能。 我们修改了下面的代码以获得 IEnumerable。
DataRow[] drow = ds.Tables[0].Select("ID ='" + id + "'");
自
DataRow[] drow =
(
from item in ds.Tables[0].AsEnumerable()
where item["ID"].ToString() == id
select item
).ToArray();
它很成功,工作正常。注意:ds 是一个数据集对象。
我们还有另一种情况来根据条件过滤行,例如
DataRow[] maxBalRow = ds.Tables[0].Select("BALANCE = MAX(BALANCE)");
在这里我们无法解决,因为条件包含"MAX"数据库函数。
您可以使用以下命令将DataTable
转换为数组(Tim Schmelter 在评论中的建议):
DataRow[] drow = ds.Tables[0].Select();
之后,您可以执行查询,例如:
DataRow item = drow.FirstOrDefault(row => row["ID"] == id);
和
// get the max balance first
double maxBalance = drow.Max(row => (double)row["BALANCE"]);
// search for items with the max balance
DataRow[] item = drow.Where(row => row["BALANCE"] == maxBalance).ToArray();
另一种解决方案是按照 asc 顺序对表进行排序字段"余额"并选择最后一行。
DataRow[] myrows= ds.Tables[0].Select("","BALANCE ASC");
DataRow rowtoget=myrows[myrows.Length-1];
希望对您有所帮助。
我认为寻找 ID,您应该使用 table.Rows.Find()
方法,它比表扫描快得多。
ds.Tables[0].Rows.Find(id);
搜索MAX(BALANCE)
(以及所有匹配的行),您必须执行表扫描。与其进行两次扫描(确定最大值并比较它们),不如将它们组合在一次扫描中:
// list of balances.
var maxBalances = new List<DataRow>();
// initial value
double maxBalance = 0;
// check each row
foreach(var row in ds.Tables[0])
{
// read the value
var value = (double)row["BALANCE"];
// if the value is higher than the previous balance, forget all previous selected rows.
if(value > maxBalance)
{
// set the new maxBalance value.
maxBalance = value;
// clear the list
maxBalances.Clear();
}
// if the value == maxBalance, add it to the list.
if(value == maxBalance)
maxBalances.Add(row);
}
// maxBalances contains all rows who share the highest balance.