我在datatable中有两列:
ID, Calls.
我该如何查找ID = 5时Calls的值?其中5可以是任何数字,仅为示例。每一行都有唯一的ID。
制定一个字符串搜索条件,就像这样:
string searchExpression = "ID = 5"
然后使用DataTable
对象的.Select()
方法,就像这样:
DataRow[] foundRows = YourDataTable.Select(searchExpression);
现在你可以像这样循环遍历结果:
int numberOfCalls;
bool result;
foreach(DataRow dr in foundRows)
{
// Get value of Calls here
result = Int32.TryParse(dr["Calls"], out numberOfCalls);
// Optionally, you can check the result of the attempted try parse here
// and do something if you wish
if(result)
{
// Try parse to 32-bit integer worked
}
else
{
// Try parse to 32-bit integer failed
}
}
var rows = dt.AsEnumerable()
.Where(r=> r.Field<int>("ID") == 5);
由于每行都有唯一的ID,因此您应该使用 Single/SingleOrDefault
。如果返回多个记录,它将抛出异常。
DataRow dr = dt.AsEnumerable()
.SingleOrDefault(r=> r.Field<int>("ID") == 5);
(将int
替换为你的ID字段类型)
我可以使用以下代码。 谢谢大家。
int intID = 5;
DataTable Dt = MyFuctions.GetData();
Dt.PrimaryKey = new DataColumn[] { Dt.Columns["ID"] };
DataRow Drw = Dt.Rows.Find(intID);
if (Drw != null) Dt.Rows.Remove(Drw);
DataRow[] rows = table.Select("ID = 7");
DataRow dataRow = dataTable.AsEnumerable().FirstOrDefault(r => Convert.ToInt32(r["ID"]) == 5);
if (dataRow != null)
{
// code
}
如果它是一个类型化的DataSet:
MyDatasetType.MyDataTableRow dataRow = dataSet.MyDataTable.FirstOrDefault(r => r.ID == 5);
if (dataRow != null)
{
// code
}
你好,只需创建一个简单的函数,如下所示... 它将返回所有输入参数为有效或真的行。
public DataTable SearchRecords(string Col1, DataTable RecordDT_, int KeyWORD)
{
TempTable = RecordDT_;
DataView DV = new DataView(TempTable);
DV.RowFilter = string.Format(string.Format("Convert({0},'System.String')",Col1) + " LIKE '{0}'", KeyWORD);
return DV.ToTable();
}
只需按照以下方式调用即可:
DataTable RowsFound=SearchRecords("IdColumn", OriginalTable,5);
其中5是ID。
谢谢。试试这段代码
DataRow foundRow = FinalDt.Rows.Find(Value);
但是至少要设置一个主键。
如果必要,尽量避免不必要的循环,可以采用这种方法。
string SearchByColumn = "ColumnName=" + value;
DataRow[] hasRows = currentDataTable.Select(SearchByColumn);
if (hasRows.Length == 0)
{
//your logic goes here
}
else
{
//your logic goes here
}