﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ExtensionMethods.DataExpand
{
    public static class DataTableExpand
    {
        public static DataRow FirstRow(this DataTable @this)
        {
            if (@this.IsNotNull())
            {
                return @this.Rows[0];
            }
            else
            {
                return null;
            }

        }

        public static List<DataRow> DtToList(this DataTable dt)
        {
            return dt.AsEnumerable().ToList();
        }

        public static bool IsNull(this DataTable dt)
        {
            return dt == null || dt.Rows.Count == 0;
        }

        public static bool IsNotNull(this DataTable dt)
        {
            return dt != null && dt.Rows.Count > 0;
        }

        public static IEnumerable<dynamic> ToExpandoObjects(this DataTable @this)
        {
            var list = new List<dynamic>();

            foreach (DataRow dr in @this.Rows)
            {
                dynamic entity = new ExpandoObject();
                var expandoDict = (IDictionary<string, object>)entity;

                foreach (DataColumn column in @this.Columns)
                {
                    expandoDict.Add(column.ColumnName, dr[column]);
                }


                list.Add(entity);
            }

            return list;
        }
    }
}
