Sunday, 27 August 2017

Convert DataSet To List Or GenericList Using LINQ - C#


Introduction
In this article we will learn how to convert dataset to list or convert DataSet to List of collection o generic list in c#. Convert DataSet into List using LINQ. 


Many times we face this condition when we need to convert our DatSet data into a List of Collection. So here you can find the best solution of this Using LINQ.

Suppose i have a DataSet data looks like give below image


Now i want to convert this dataset data into List of collection.
List<Employee> lstEmployee = ds.Tables[0].AsEnumerable().Select(
                            dataRow => new Employe
                            {
                                EmpID = dataRow.Field<int>("EmpID"),
                                EmpCode = dataRow.Field<int>("EmpCode"),
                                EmpName = dataRow.Field<string>("EmpName")
                            }).ToList();
Using LINQ we simply read the List. To perform linq over DataSet we use the AsEnumerable() property to apply linq on dataset.
In this example i have a DataSet and i am retrieving its data into a List of Employee object. Emplyoee is my entity which has EmpID , EmpName and EmpCode property fields.

Here is the Output 

Also interested - . Top 30 Asp.net interview question.



If you are working with Procedure data or table data in you DAL layer then this below example is helpful for you.
SqlConnection con = new SqlConnection("Data Source=DESKTOP\\SQLEXPRESS;
                    Initial Catalog = TsetDB; Integrated Security = True");

    List<Employee> lstEmployee = new List<Employee>();
            Employee emp = new Employee();

            SqlCommand cmd = new SqlCommand("SELECT * FROM Employee", con);
            con.Open();
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            if (ds != null)
            {

                lstEmployee = ds.Tables[0].AsEnumerable().Select(
                          dataRow => new Employe
                          {
                              EmpID = dataRow.Field<int>("EmpID"),
                              EmpCode = dataRow.Field<int>("EmployeeCode"),
                            EmpName = dataRow.Field<string>("EmployeeName")
                          }).ToList();

            }

Read Here What is the difference between null and undefinedCheck for null vs ndefined in javascript.




No comments:

Post a Comment