Wednesday, June 14, 2017

How to Convert Dataset or DataTable to List collection

Some time we need to convert Dataset or DataTable values to List items for easy filter or any search in the data. List collection have more feature compare then Dataset. Like we can select top 3 users or role is admin or etc. So we can write own LINQ query in the list and get relevant information without using any loop. This will help to improve you application performance as well.

The given below example I have one userdetails class have properties of user information and another one is data set to list conversion method. If you pass dataset to the function then the function will return collection of userdetails list.

Sample Code:


Convert DataSet to List Function:
        public IList ConvertToList(DataSet ds)
        {
            List lst = new List();
            try
            {
                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    var myData = ds.Tables[0].AsEnumerable().Select(r => new UserDetails
                    {
                        UserID = r.Field("UserID"),
                        UserName = r.Field("Username"),
                        EmailID = r.Field("EmailID"),
                        Name = r.Field("DisplayName"),
                        RoleID = r.Field("RoleID").ToString(),
                        Sex = r.Field("Sex"),
                        DOB = r.Field("DOB"),
                        Mobile = r.Field("Mobile"),
                        IsActive = r.Field("IsActive")
                    });
                    lst = myData.ToList();
                }
            }
            catch (Exception ex)
            {
                Comman.ErrorLog(ex.Message);
            }
            return lst;
        }








  
 
UserDetails.cs    
//User detail Class information
        public class UserDetails
        {
            public string UserID { get; set; }
            public string UserName { get; set; }
            public string EmailID { get; set; }
            public string Name { get; set; }
            public string RoleID { get; set; }
            public string Sex { get; set; }
            public DateTime? DOB { get; set; }
            public string Mobile { get; set; }
            public bool IsActive { get; set; }
        }



1 comment:

Durga IT Solutions said...
This comment has been removed by the author.