在具有特定id的数据表中查找行
我在数据表中有两列:
ID, Calls.
如何where 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 } }
您可以使用LINQ to DataSet / DataTable
var rows = dt.AsEnumerable() .Where(r=> r.Field("ID") == 5);
由于每一行都有一个唯一的ID,因此您应该使用Single/SingleOrDefault
,如果您获得多个记录,则会抛出exception。
DataRow dr = dt.AsEnumerable() .SingleOrDefault(r=> r.Field("ID") == 5);
(将int
替换为您的ID字段的类型)
您可以尝试使用方法选择
DataRow[] rows = table.Select("ID = 7");
我可以使用以下代码。 感谢大家。
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 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 }
试试这段代码
DataRow foundRow = FinalDt.Rows.Find(Value);
但设置至少一个主键
您好,只需创建一个如下所示的简单函数。它返回输入的调用参数有效或为真的所有行。
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。 谢谢..
尝试避免不必要的循环,并在需要时进行此操作。
string SearchByColumn = "ColumnName=" + value; DataRow[] hasRows = currentDataTable.Select(SearchByColumn); if (hasRows.Length == 0) { //your logic goes here } else { //your logic goes here }
如果要按特定ID进行搜索,则表中应该有一个主键。