Home:ALL Converter>How to filter a specific value from a data table

How to filter a specific value from a data table

Ask Time:2012-06-11T19:42:35         Author:Running Rabbit

Json Formatter

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?

Author:Running Rabbit,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/10979391/how-to-filter-a-specific-value-from-a-data-table
Jake1164 :

Have you looked into the DataTable.Select() method?\n\nhttp://msdn.microsoft.com/en-us/library/system.data.datatable.select(v=vs.100).aspx\n\npublic class DataTableExample \n{ \n public static void Main() \n { \n //adding up a new datatable \n DataTable dtEmployee = new DataTable(\"Employee\"); \n //adding up 3 columns to datatable \n dtEmployee.Columns.Add(\"ID\", typeof(int)); \n dtEmployee.Columns.Add(\"Name\", typeof(string)); \n dtEmployee.Columns.Add(\"Salary\", typeof(double)); \n //adding up rows to the datatable \n dtEmployee.Rows.Add(52, \"Human1\", 21000); \n dtEmployee.Rows.Add(63, \"Human2\", 22000); \n dtEmployee.Rows.Add(72, \"Human3\", 23000); \n dtEmployee.Rows.Add(110,\"Human4\", 24000); \n // sorting the datatable basedon salary in descending order \n DataRow[] rows= dtEmployee.Select(string.Empty,\"Salary desc\"); \n //foreach datatable \n foreach (DataRow row in rows) \n { \n Console.WriteLine(row[\"ID\"].ToString() + \":\" + row[\"Name\"].ToString() + \":\" + row[\"Salary\"].ToString()); \n } \n Console.ReadLine(); \n } \n}\n",
2012-06-11T11:49:00
Jon Skeet :

Three options:\n\n\nUse DataTable.Select, providing a filter expression\nIterate over the rows yourself\nUse LINQ, with the data table extensions\n\n\nPersonally I'd suggest using the last option (LINQ):\n\nvar row = table.AsEnumerable()\n .FirstOrDefault(r => r.Field<string>(\"AccountID\") == accountID);\nif (row != null)\n{\n // Use the row\n}\n",
2012-06-11T11:46:08
yy