Thursday, January 25, 2018

LINQ with DataTable ( c# / .NET )



In .NET, LINQ has made us easier to query and manipulate most of the data sources along with DataTables. DataTables can be parsed as enumerable and hence can be easily manipulated by LINQ. This has made developers very easier to play with data of the datatable. Fetching, filtering and selection of data within DataTables would not be so easy without linq. The below sample code in console application proves it. The code populates some dummy data inside a datatable, uses linq to filter the datatable and uses the filtered values to display it in console window. You can take this reference as implement it in your code.

Note: The following namespaces are required : 

using System.Data;
using System.Linq;

Code :

class Program
    {
        static void Main(string[] args)
        {
            // Datatable variable 'dt' with columns ID,Name
            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Name"typeof(string));

            // loading dummy data to the datatable
            DataRow dr1 = dt.NewRow(); dr1["ID"] = 1; dr1["Name"] = "John"; dt.Rows.Add(dr1);
            DataRow dr2 = dt.NewRow(); dr2["ID"] = 2; dr2["Name"] = "Peter"; dt.Rows.Add(dr2);
            DataRow dr3 = dt.NewRow(); dr3["ID"] = 3; dr3["Name"] = "Misha"; dt.Rows.Add(dr3);
            DataRow dr4 = dt.NewRow(); dr4["ID"] = 4; dr4["Name"] = "Pema"; dt.Rows.Add(dr4);

            // converting datatable to enumerable and using lambda expression to get filtered enumerable data row collection
            // it filters rows from datatable with name starting from "Pe"
            EnumerableRowCollection<DataRow> filteredRows = dt.AsEnumerable().Where(x => x.Field<string>("Name").StartsWith("Pe"));

            // accessing the enumerable row collection using foreach
            foreach (var row in filteredRows.AsEnumerable())
            {
                int id = row.Field<int>("ID");
                string name = row.Field<string>("Name");
                // display the result in console
                Console.WriteLine("Name : " + name + "  with ID : " + id);

            }

            // accessing specific FirstOrDefault record using lambda expression with a filter for field "ID"
            //it picks first or default row with ID having value "4"
            DataRow specificRecord = filteredRows.AsEnumerable().FirstOrDefault(x => x.Field<int>("ID") == 4);
            int specificID = specificRecord.Field<int>("ID");
            string specificName = specificRecord.Field<string>("Name");
            // display the result in console
            Console.WriteLine("\nSpecific record Name : " + specificName + " with ID : " + specificID);

            Console.ReadKey();
        }
    }

No comments:

Post a Comment