Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Create Collection from a DataSet

0.00/5 (No votes)
7 Aug 2014 1  
This tip will help you to create a collection from a DataSet

Introduction

Since I started working in WPF, I came to know about Collections. But the tricky part here is previously I was working with Dataset, so it looks like I have started learning a new technology in the data binding perspective, because the Dataset was known to me since I started learning programming but I don't know some of its capabilities/powers either. But now in the WPF world, we used to make use of collection. Now let's start why I am here to write my first article/post/tips and tricks, etc., whatever you call it.

Background

Couple of days ago, I came up with an issue to convert DataTable to Collection in my home developed application and then I started working on this simple solution (not a higher ended solution) and I hope that will help some beginners and intermediate (maybe) developers if they have the same issue.

Code

For this demo, I was using a Person class as shown below:

/// <summary>
    /// Person Class
    /// </summary>
    public class Person
    {
        private int id;
        [XmlElement("id")]
        public int ID
        {
            get { return id; }
            set { id = value; }
        }

        private string name;
        [XmlElement("name")]
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        private string address;
        [XmlElement("address")]
        public string Address
        {
            get { return address; }
            set { address = value; }
        }

        private DateTime? dob;
        [XmlElement("dob")]
        public DateTime? DateOfBirth
        {
            get { return dob; }
            set { dob = value; }
        }

        private EmpType employeeType = EmpType.Trainee;
        [XmlElement("EmpType")]
        public EmpType EmployeeType
        {
            get { return employeeType; }
            set { employeeType = value; }
        }
    }

    /// <summary>
    /// Person Collection
    /// </summary>
    [Serializable(), XmlRoot("DocumentElement"), XmlType("Person")]
    public class PersonCollection : BindingList<Person>
    {

    }

and an Extension class for DataTable below:

public static class ExtensionsEx
    {
        private static Type collectionType;
        /// <summary>
        /// Lets you convert DataTable to BindingList
        /// </summary>
        /// <typeparam name="T">Collection type</typeparam>
        /// <param name="Dt">DataTable</param>
        /// <param name="bindingList">Collection to fill up</param>
        /// <returns></returns>
        public static Collection<T> GetCollectionfromDataTable<T>
        (this DataTable Dt, Collection<T> bindingList)
        {
            try
            {
                collectionType = bindingList.GetType();
                if (ValidateDataSet<T>(Dt))
                    using (System.IO.MemoryStream xmlStream = new System.IO.MemoryStream())
                    {
                        Dt.WriteXml(xmlStream, XmlWriteMode.IgnoreSchema);

#if DEBUG
                        xmlStream.Position = 0;
                        XmlDocument xd = new XmlDocument();
                        xd.Load(xmlStream);
#endif
                        xmlStream.Position = 0;
                        using (System.Xml.XmlTextReader collectionReader = 
                                new System.Xml.XmlTextReader(xmlStream))
                        {
                            XmlSerializer serializer = new XmlSerializer(collectionType);
                            bindingList = (Collection<T>)serializer.Deserialize(collectionReader);
                        }
                    }
                return bindingList;
            }
            catch { return null; }
        }

        /// <summary>
        /// Just to validate DataTable if it has Name of the Type T.
        /// </summary>
        /// <typeparam name="T"> Type </typeparam>
        /// <param name="Dt">DataTable</param>
        /// <returns> bool </returns>
        private static bool ValidateDataSet<T>(DataTable Dt)
        {
            var s = typeof(T);
            if (collectionType == null) return false;
            if (string.IsNullOrWhiteSpace(Dt.TableName))
            {
                Dt.TableName = s.Name;
                Dt.AcceptChanges();
            }
            return true;
        }
    }

Points of Interest

If your application requires different random number sequences, invoke this constructor repeatedly with different seed values. One way to produce a unique seed value is to make it time-dependent. For example, derive the seed value from the system clock. However, the system clock might not have sufficient resolution to provide different invocations of this constructor with a different seed value (http://msdn.microsoft.com/en-us/library/vstudio/ctssatww(v=vs.100).aspx).

History

This is my first tip. Hope it helps. I will update this soon to support all kinds of data types after learning about them.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here