mmushtaq
mmushtaq

Reputation: 3520

Convert DataTable to String Array through Extension Method

I know there are plenty of similar threads out there but my requirement is little different. The basic requirement is to convert a DataTable to array of strings. I am able to do that by creating an Extension method to do that work for me.

public static class ExtensionMethods
{
     public static object ToStringArray(this DataTable dt, params object[] columns)
     {
          //if specifically columns are provided then returns item array values for these columns.
          if (columns != null && columns.Length > 0)
          {
              //return dt.AsEnumerable().Select(x => new[] { //here i want to iterate through columns params }).ToArray();
          }
          else
          {
               return dt.AsEnumerable().Select(x => new[] { x.ItemArray }).ToArray();
          }
      }    
}

If I don't provide column names explicitly then it perfectly returns all rows values as strings array.

var dtData = dataTable.ToStringArray();

But what if i provide column names

var dtData = dataTable.ToStringArray("Column1", "Column2", "Column3");

then how can I iterate through columns to get only provided columns values in this chunk of code

if (columns != null && columns.Length > 0)
{
     return dt.AsEnumerable().Select(x => new[] { //here i want to iterate through columns params }).ToArray();
}

I know I can do that by hard coding the column names as follow:

var dtData = dt.AsEnumerable().Select(x => new[] { x["Column1"], x["Column2"], x["Column3"] }).ToArray();

or

var dtData = dt.AsEnumerable().Select(x => new[] { x.Field<string>("Column1"), x.Field<int>("Column2").ToString(), x.Field<string>("Column3") }).ToArray();

How can I get this working in my Extension method and by using param object[] columns values?

Upvotes: 0

Views: 2652

Answers (1)

Vijay
Vijay

Reputation: 136

You could do a select on the columns parameter. I have changed the type from object[] to string[] here.

public static class ExtensionMethods
{
    public static object ToStringArray(this DataTable dt, params string[] columns)
    {
        //if specifically columns are provided then returns item array values for these columns.
        if (columns != null && columns.Length > 0)
        {
            return dt.AsEnumerable().Select(x => columns.Select(c => x[c]).ToArray()).ToArray();
        }
        else
        {
            return dt.AsEnumerable().Select(x => new[] { x.ItemArray }).ToArray();
        }
    }
}

Upvotes: 3

Related Questions