Getting the values from a Datatable column

I couldn't find any better, reusable way to get all the values from a specific column of a datatable, strongly typed than the snippet below:

        internal class DataColumnConverter<T>
        {
            internal T[] GetValuesAsArray(DataTable data, string columnName)
            {
                List<T> values = new List<T>();
                foreach (DataRow r in data.Rows)
                {
                    values.Add((T)r[columnName]);
                }
                return values.ToArray();
            }
        }

Things it's missing:

  • Type Cast checking on the type of items in the DataTables' column that's specified
  • Checking that the column specified exists
  • Handling of a column which contains nullable values (Could <T> be passed as, for example int? to cater for this? maybe! Or perhaps null's could be stripped out...)

About Rob

I've been interested in computing since the day my Dad purchased his first business PC (an Amstrad PC 1640 for anyone interested) which introduced me to MS-DOS batch programming and BASIC.

My skillset has matured somewhat since then, which you'll probably see from the posts here. You can read a bit more about me on the about page of the site, or check out some of the other posts on my areas of interest.

No Comments

Add a Comment