How to filter a specific value from a data table

I have five rows in my data table (with column AccountId, Name, Email, Address) and I want to get a specific row on basis of AccountId as all the five rows have different AccountID. I want to filter it on the basis of AccountID. I mean I only need one row from the Data table to process on the basis of AccountId.

How do I get a specfic row from the data table containing the AccountId that I have passed?


Three options:

  • Use DataTable.Select, providing a filter expression
  • Iterate over the rows yourself
  • Use LINQ, with the data table extensions

Personally I'd suggest using the last option (LINQ):

var row = table.AsEnumerable()
               .FirstOrDefault(r => r.Field<string>("AccountID") == accountID);
if (row != null)
    // Use the row

Have you looked into the DataTable.Select() method?

public class DataTableExample 
    public static void Main()     
        //adding up a new datatable         
        DataTable dtEmployee = new DataTable("Employee");            
        //adding up 3 columns to datatable         
        dtEmployee.Columns.Add("ID", typeof(int));         
        dtEmployee.Columns.Add("Name", typeof(string));         
        dtEmployee.Columns.Add("Salary", typeof(double));           
        //adding up rows to the datatable         
        dtEmployee.Rows.Add(52, "Human1", 21000);         
        dtEmployee.Rows.Add(63, "Human2", 22000);         
        dtEmployee.Rows.Add(72, "Human3", 23000);         
        dtEmployee.Rows.Add(110,"Human4", 24000);           
        // sorting the datatable basedon salary in descending order        
        DataRow[] rows= dtEmployee.Select(string.Empty,"Salary desc");           
        //foreach datatable         
        foreach (DataRow row in rows)         
            Console.WriteLine(row["ID"].ToString() + ":" + row["Name"].ToString() + ":" + row["Salary"].ToString());         

Example with an array:

Example with a single Object:

Just use something like this:

DataTable dt = new DataTable();
DataRow dr = dt.Rows.Find(accntID);

Hope this helped you out.

Need Your Help

last Monday for not current date

php datetime

date('Y-m-d', strtotime("last Monday"))

Spring: Same object, different validation

validation spring

I have an object called User where I save all the data of the User. I have some annotations to perform validation and it works fine.