在数据表中查找特定id的行

46

我在datatable中有两列:

ID, Calls. 

我该如何查找ID = 5时Calls的值?其中5可以是任何数字,仅为示例。每一行都有唯一的ID。


你不能将这个操作作为select语句的一部分吗? "SELECT ID, Calls FROM MyTable WHERE ID=@id_search"。然后只需向数据库调用提供“@id_search”参数即可。这比使用LINQ更快,特别是在假定ID是主键或已索引的情况下。 - drew_w
很抱歉,不是数据库,而是数据集/数据表。 - RSM
8个回答

76

制定一个字符串搜索条件,就像这样:

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

    }
}

1
这确实给了我数据行,但是我如何从列调用中获取特定值? - RSM
@RyanMurphy - 更新了答案,展示如何从行中获取值并安全地尝试解析该值。 - Karl Anderson
@RyanMurphy - 没问题,如果您还没有投票,请随意为答案投票。 :-) - Karl Anderson
如果我想获取结果的行号,该怎么做? - Si8

56
你可以使用LINQ来操作DataSet/DataTable。
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字段类型)


1
有时候使用这个 "DataRow[] foundRows = YourDataTable.Select(searchExpression);" 无法选择表中的行。但是当我使用LINQ时,它工作得很好。感谢Habib。 - Karthikeyan P

13

我可以使用以下代码。 谢谢大家。

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);

谢谢你指出数据表可以有主键!我之前不知道这个存在,而这对我的情况产生了巨大的性能差异。 - Joe Schrag

11
你可以尝试使用选择方法。
DataRow[] rows = table.Select("ID = 7");

5
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
}

2

你好,只需创建一个简单的函数,如下所示... 它将返回所有输入参数为有效或真的行。

 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。

谢谢。

2

试试这段代码

DataRow foundRow = FinalDt.Rows.Find(Value);

但是至少要设置一个主键。


1
性能应该是每个Ms文档中的O(log n)操作:https://learn.microsoft.com/en-us/dotnet/api/system.data.datarowcollection.find?view=netframework-4.7.2 - dier

1

如果必要,尽量避免不必要的循环,可以采用这种方法。

string SearchByColumn = "ColumnName=" + value;
DataRow[] hasRows = currentDataTable.Select(SearchByColumn);
if (hasRows.Length == 0)
{
    //your logic goes here
}
else
{
    //your logic goes here
}

如果您想按特定ID进行搜索,则表中应该有一个主键。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接