zoukankan      html  css  js  c++  java
  • Find row in datatable with specific id

    Find row in datatable with specific id

    回答1

    Make a string criteria to search for, like this:

    string searchExpression = "ID = 5"
    

    Then use the .Select() method of the DataTable object, like this:

    DataRow[] foundRows = YourDataTable.Select(searchExpression);
    

    Now you can loop through the results, like this:

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

    回答2

    You can use LINQ to DataSet/DataTable

    var rows = dt.AsEnumerable()
                   .Where(r=> r.Field<int>("ID") == 5);
    

    Since each row has a unique ID, you should use Single/SingleOrDefault which would throw exception if you get multiple records back.

    DataRow dr = dt.AsEnumerable()
                   .SingleOrDefault(r=> r.Field<int>("ID") == 5);
    

    (Substitute int for the type of your ID field)

  • 相关阅读:
    07组合,模版
    06享元、责任链
    05观察,命令
    04代理,迭代器
    03单例,策略
    02工厂,创建者
    01基础
    css随记02布局
    css随记01编辑技巧,背景与边框
    nodejs随记03
  • 原文地址:https://www.cnblogs.com/chucklu/p/15357168.html
Copyright © 2011-2022 走看看