简体   繁体   中英

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?

http://msdn.microsoft.com/en-us/library/system.data.datatable.select(v=vs.100).aspx

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

Example with an array: http://msdn.microsoft.com/en-us/library/f6dh4x2h(VS.80).aspx

Example with a single Object: http://msdn.microsoft.com/en-us/library/ydd48eyk

Just use something like this:

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

Hope this helped you out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM