Check if String / Record exists in DataTable

前端 未结 4 667
既然无缘
既然无缘 2020-12-30 08:59

I have a String and I need to check if any column \"item_manuf_id\" in DataTable dtPs.Rows equals to certain value

I can loop over all Rows and compare



        
4条回答
  •  粉色の甜心
    2020-12-30 09:46

    You can loop over each row of the DataTable and check the value.

    I'm a big fan of using a foreach loop when using IEnumerables. Makes it very simple and clean to look at or process each row

    DataTable dtPs = // ... initialize your DataTable
    foreach (DataRow dr in dtPs.Rows)
    {
        if (dr["item_manuf_id"].ToString() == "some value")
        {
            // do your deed
        }
    }
    

    Alternatively you can use a PrimaryKey for your DataTable. This helps in various ways, but you often need to define one before you can use it.

    An example of using one if at http://msdn.microsoft.com/en-us/library/z24kefs8(v=vs.80).aspx

    DataTable workTable = new DataTable("Customers");
    
    // set constraints on the primary key
    DataColumn workCol = workTable.Columns.Add("CustID", typeof(Int32));
    workCol.AllowDBNull = false;
    workCol.Unique = true;
    
    workTable.Columns.Add("CustLName", typeof(String));
    workTable.Columns.Add("CustFName", typeof(String));
    workTable.Columns.Add("Purchases", typeof(Double));
    
    // set primary key
    workTable.PrimaryKey = new DataColumn[] { workTable.Columns["CustID"] };
    

    Once you have a primary key defined and data populated, you can use the Find(...) method to get the rows that match your primary key.

    Take a look at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx

    DataRow drFound = dtPs.Rows.Find("some value");
    if (drFound["item_manuf_id"].ToString() == "some value")
    {
        // do your deed
    }
    

    Finally, you can use the Select() method to find data within a DataTable also found at at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx.

    String sExpression = "item_manuf_id == 'some value'";
    DataRow[] drFound;
    drFound = dtPs.Select(sExpression);
    
    foreach (DataRow dr in drFound)
    {
        // do you deed. Each record here was already found to match your criteria
    }
    

提交回复
热议问题