Search code examples
c#datatable

Converting or casting DataTable types


I have a number of classes that look like, for example

public class VarcharTokens : DataTable
{
  public VarcharTokens()
  {
    Columns.Add("Value", typeof(string));
  }
}

What I want to be able to do is read from one database and write to another, passing a DataTable between the two. If the source returns a DataTable and the destination expects a VarcharTokens then I need a highly efficient method to cast, convert or otherwise handle the difference in types.

I suppose DataTable extension methods would work, somehow. I tried looking at explicit/implicit operators but user-defined conversions to or from a base type are not allowed.

What are my options?

If at all possible I would like not to end up with 2 copies of the data; the quantities of data are truly colossal in my use-case.


Solution

  • The solution I came up with was an extension method as follows

            public static VarcharTokens ToVarcharTokens(this DataTable dt)
            {
                var result = new VarcharTokens();
    
                dt.AsEnumerable().All(r => { result.Rows.Add().ItemArray = r.ItemArray; return true; });
    

    which I subsequently generalised like this

        public static T DTConvert<T>(this DataTable dt) where T:DataTable, new ()
        {
            try
            {
                T result = new T();
    
                dt.AsEnumerable().All(r => { result.Rows.Add().ItemArray = r.ItemArray; return true; });
    
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception($"UDTConversionError to {typeof(T)} : {ex.Message}"); 
            }
        }