46

I have two columns in a datatable:

ID, Calls. 

How do I find what the value of Calls is where ID = 5?

5 could be anynumber, its just for example. Each row has a unique ID.

RSM
  • 14,540
  • 34
  • 97
  • 144
  • Couldn't you do this as part of the select statement? "SELECT ID, Calls FROM MyTable WHERE ID=@id_search". Then just provide the "@id_search" parameter to the database call. This is going to be faster than LINQ, especially assuming ID is a primary key or indexed. – drew_w Dec 17 '13 at 15:43
  • Not a database, dataset/datatable im afraid. – RSM Dec 17 '13 at 15:44

8 Answers8

76

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

    }
}
Karl Anderson
  • 34,606
  • 12
  • 65
  • 80
55

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)

Habib
  • 219,104
  • 29
  • 407
  • 436
  • 1
    Some time unable select rows from table using this "DataRow[] foundRows = YourDataTable.Select(searchExpression);". But when I am using LINQ. Its working good. Thanks Habib. – Karthikeyan P Jan 28 '16 at 10:08
13

I could use the following code. Thanks everyone.

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);
Kamil KIZILTAŞ
  • 131
  • 1
  • 2
  • Thanks for pointing out that a datatable can have a primary key! Wasn't aware that existed, and that made a huge performance difference in my case. – Joe Schrag Aug 25 '23 at 15:00
11

You can try with method select

DataRow[] rows = table.Select("ID = 7");
marcello
  • 111
  • 1
  • 2
5
DataRow dataRow = dataTable.AsEnumerable().FirstOrDefault(r => Convert.ToInt32(r["ID"]) == 5);
if (dataRow != null)
{
    // code
}

If it is a typed DataSet:

MyDatasetType.MyDataTableRow dataRow = dataSet.MyDataTable.FirstOrDefault(r => r.ID == 5);
if (dataRow != null)
{
    // code
}
va.
  • 848
  • 3
  • 17
  • 39
2

try this code

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

but set at lease one primary key

Tanmay Nehete
  • 2,138
  • 4
  • 31
  • 42
  • 1
    performance should be an O(log n) operation per Ms docs: https://learn.microsoft.com/en-us/dotnet/api/system.data.datarowcollection.find?view=netframework-4.7.2 – dier Feb 08 '19 at 20:43
2

Hello just create a simple function that looks as shown below.. That returns all rows where the call parameter entered is valid or true.

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

and simply call it as shown below;

  DataTable RowsFound=SearchRecords("IdColumn", OriginalTable,5);

where 5 is the ID. Thanks..

Sunday Efeh
  • 81
  • 1
  • 1
1

Try avoiding unnecessary loops and go for this if needed.

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

If you want to search by specific ID then there should be a primary key in a table.

Mohd Sadiq
  • 11
  • 2