溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

c# 之DataTable的擴(kuò)展方法

發(fā)布時間:2020-05-19 17:07:23 來源:網(wǎng)絡(luò) 閱讀:1209 作者:SmallHan 欄目:編程語言

    由于太懶了,很久沒更新了。畢業(yè)了,得好好裝逼學(xué)習(xí)了,不能一心想著完了。

    由于公司中的項目大量的使用DataTable,而每次對datatable進(jìn)行操作的時候需要寫很多相同的代碼,所以秉著 裝逼而學(xué)習(xí) 的態(tài)度,于是擼了幾個擴(kuò)展方法,記錄下來,學(xué)習(xí)下。

    class Program
    {
        public DataTable LinqTable = new DataTable();
        void AddNewRow(int id, string name)
        {
            Random random = new Random();
            DataRow newRow = LinqTable.NewRow();
            Thread.Sleep(20);
            newRow["id"] = id;
            newRow["name"] = id + name;
            newRow["salary"] = (float)random.Next(10000) / 100;
            LinqTable.Rows.Add(newRow);
        }
        void MyTable()
        {
            LinqTable.Columns.Add(new DataColumn("id", typeof(int)));
            LinqTable.Columns.Add(new DataColumn("name", typeof(string)));
            LinqTable.Columns.Add(new DataColumn("salary", typeof(float)));
        }
        static void Main(string[] args)
        {
            Program program = new Program();
            program.MyTable();
            AddData(program);
            ForEach(program);
            Select(program);
            SelectOne(program);
            Contains(program);
            SingleOrDefault(program);
            AddColumnFiled(program);
            AddColumnFiledTwo(program);
            Max(program);
            Console.ReadKey();
        }

        /// <summary>
        /// 給DataTable中的每條記錄執(zhí)行某個操作
        /// </summary>
        /// <param name="table">DataTable</param>
        /// <param name="func">Func委托</param>
        static void ForEach(Program program)
        {
            Console.WriteLine("給DataTable中的每條記錄執(zhí)行某個操作");
            ExMethod.ForEach(program.LinqTable, (DataRow row) =>
            {
                row["id"] = int.Parse(row["id"].ToString()) * 10;
            });
            for (var i = 0; i < program.LinqTable.Rows.Count; i++)
            {
                DataRow row = program.LinqTable.Rows[i];
                foreach (var it in row.ItemArray)
                {
                    Console.Write(it + " ");
                }
                Console.WriteLine();
            }
            Console.WriteLine();
        }

        /// <summary>
        /// 從DataTable中獲取某個字段組成的集合
        /// </summary>
        /// <typeparam name="T">字段的數(shù)據(jù)類型</typeparam>
        /// <param name="table">DataTable</param>
        /// <param name="selector">Func委托</param>
        /// <returns>IEnumerable</returns>
        static void Select(Program program)
        {
            Console.WriteLine("從DataTable中獲取某個字段組成的集合");
            List<int> list = (List<int>)ExMethod.Select<int>(program.LinqTable, "id");
            foreach (var it in list)
            {
                Console.WriteLine(it);
            }
            Console.WriteLine();
        }

        /// <summary>
        /// 獲取DataTable中某個字段符合給定條件的處理過的集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <param name="name"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        static void SelectOne(Program program)
        {
            Console.WriteLine("獲取DataTable中某個字段符合給定條件的處理過的集合");
            List<int> list = (List<int>)ExMethod.Select<int>(program.LinqTable, "id", (int x) =>
            {
                return x + 10;
            });
            foreach (var it in list)
            {
                Console.WriteLine(it);
            }
            Console.WriteLine();
        }

        /// <summary>
        /// 判斷給定DataTable中是否存在某個字段值符合給定條件的記錄
        /// </summary>
        /// <typeparam name="T">給定字段的數(shù)據(jù)類型</typeparam>
        /// <param name="table">DataTable</param>
        /// <param name="name">字段名稱</param>
        /// <param name="predicate">Func委托</param>
        /// <returns>True/False</returns>
        static void Contains(Program program)
        {
            Console.WriteLine("判斷給定DataTable中是否存在某個字段值符合給定條件的記錄");
            bool flg = ExMethod.Contains<String>(program.LinqTable, "name", (string name) =>
            {
                return name.Equals("1 Max");
            });
            Console.WriteLine(flg.ToString());
            Console.WriteLine();
        }

        /// <summary>
        /// 獲取DataTable中符合某個條件的唯一記錄
        /// </summary>
        /// <param name="table">DataTable</param>
        /// <param name="predicate">Func委托</param>
        /// <returns></returns>
        static void SingleOrDefault(Program program)
        {
            Console.WriteLine("獲取DataTable中符合某個條件的唯一記錄");
            DataRow row = ExMethod.SingleOrDefault<int>(program.LinqTable, "id", (int i) =>
            {
                return i == 10;
            });
            if (row != null)
            {
                foreach (var it in row.ItemArray)
                {
                    Console.Write(it + " ");
                }
                Console.WriteLine();
            }
            Console.WriteLine();

        }

        /// <summary>
        /// 添加指定的列
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <param name="columnFiled"></param>
        static void AddColumnFiled(Program program)
        {
            Console.WriteLine("添加指定的列");
            ExMethod.AddColumnFiled<string>(program.LinqTable, "sex");
            Console.WriteLine(program.LinqTable.Columns.Count);
            Console.WriteLine();
        }

        /// <summary>
        /// 添加指定的列并且附默認(rèn)值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <param name="columnFiled"></param>
        /// <param name="value"></param>
        static void AddColumnFiledTwo(Program program)
        {
            Console.WriteLine("添加指定的列并且附默認(rèn)值");
            ExMethod.AddColumnFiled<string>(program.LinqTable, "job", "碼農(nóng)");
            for (int i = 0; i < program.LinqTable.Rows.Count; i++)
            {
                DataRow row = program.LinqTable.Rows[i];
                foreach (var it in row.ItemArray)
                {
                    Console.Write(it + " ");
                }
                Console.WriteLine();
            }
            Console.WriteLine();
        }

        /// <summary>
        ///  DataTable中某個字段具有最大值的記錄
        /// </summary>
        /// <param name="program"></param>
        static void Max(Program program)
        {
            Console.WriteLine("DataTable中某個字段具有最大值的記錄");
            DataRow row = ExMethod.Max<float>(program.LinqTable.Rows, () =>
            {
                return "salary";
            });
            foreach (var it in row.ItemArray)
            {
                Console.Write(it + " ");
            }
            Console.WriteLine();
        }

        #region 錄入數(shù)據(jù)
        static void AddData(Program program)
        {
            program.AddNewRow(1, " 小瀚");
            program.AddNewRow(2, " 小明");
            program.AddNewRow(3, " 小杰");
            program.AddNewRow(4, " 小黃");
            program.AddNewRow(5, " 小白");
            program.AddNewRow(6, " 小李");
            program.AddNewRow(7, " 張三");
            program.AddNewRow(8, " 李四");
            program.AddNewRow(9, " 帥哥");
            program.AddNewRow(10, " CC");
        }
        #endregion
    }

以下是擴(kuò)展方法

  public static class ExMethod
    {
        /// <summary>
        ///  給DataTable中的每條記錄執(zhí)行某個操作
        /// </summary>
        /// <param name="table"></param>
        /// <param name="action"></param>
        public static void ForEach(this DataTable table, Action<DataRow> action)
        {
            for (int i = 0; i < table.Rows.Count; i++)
            {
                DataRow current = table.Rows[i];
                action(current);
            }
        }


        /// <summary>
        /// 從DataTable中獲取某個字段組成的集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static IEnumerable<T> Select<T>(this DataTable dt, string name)
        {
            DataColumnCollection columns = dt.Columns;
            IList<T> iList = new List<T>(dt.Rows.Count);
            if (!columns.Contains(name)) return iList;
            for (var i = 0; i < dt.Rows.Count; i++)
            {
                iList.Add((T)dt.Rows[i][name]);
            }
            return iList;
        }

        /// <summary>
        ///  獲取DataTable中某個字段符合給定條件的處理過的集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <param name="name"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public static IEnumerable<T> Select<T>(this DataTable dt, string name, Func<T, T> func)
        {
            DataColumnCollection columns = dt.Columns;
            IList<T> iList = new List<T>();
            if (!columns.Contains(name)) return iList;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                iList.Add(func((T)dt.Rows[i][name]));
            }
            return iList;
        }

        /// <summary>
        /// 判斷給定DataTable中是否存在某個字段值符合給定條件的記錄
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <param name="name"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public static bool Contains<T>(this DataTable dt, string name, Func<T, bool> func)
        {
            DataColumnCollection columns = dt.Columns;
            if (!columns.Contains(name)) return false;
            foreach (DataRow row in dt.Rows)
            {
                if (func((T)row[name]))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 獲取DataTable中符合某個條件的唯一記錄
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <param name="name"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public static DataRow SingleOrDefault<T>(this DataTable dt, string name, Func<T, bool> func)
        {
            DataRow result = null;
            long count = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow current = dt.Rows[i];
                if (func((T)current[name]))
                {
                    count++;
                    result = current;
                }
            }
            switch (count)
            {
                case 0: return null;
                case 1: return result;
            }
            return result;
        }

        /// <summary>
        /// 添加指定的列
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <param name="columnFiled"></param>
        public static void AddColumnFiled<T>(this DataTable dt, string columnFiled)
        {
            if (!string.IsNullOrWhiteSpace(columnFiled))
            {
                dt.Columns.Add(columnFiled, typeof(T));
            }
        }

        /// <summary>
        /// 添加指定的列并且附默認(rèn)值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <param name="columnFiled"></param>
        /// <param name="value"></param>
        public static void AddColumnFiled<T>(this DataTable dt, string columnFiled, T value)
        {
            if (!string.IsNullOrWhiteSpace(columnFiled))
            {
                dt.Columns.Add(columnFiled, typeof(T));
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow current = dt.Rows[i];
                    current[columnFiled] = value;
                }
            }
        }

        /// <summary>
        /// DataTable中某個字段具有最大值的記錄
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collection"></param>
        /// <param name="selector"></param>
        /// <returns></returns>
        public static DataRow Max<T>(this DataRowCollection collection, Func<string> func)
        {
            string name = func();
            DataTable dt = collection[0].Table;
            DataColumnCollection columns = dt.Columns;
            if (!columns.Contains(name)) return null;
            Comparer<T> comparer = Comparer<T>.Default;
            DataRow result = null;
            T value = default(T);
            foreach (DataRow row in collection)
            {
                if (comparer.Compare(value, (T)row[name]) < 0)
                {
                    value = (T)row[name];
                    result = row;
                }
            }
            return result;
        }

    }

    以下是參考別人Deno寫的幾個擴(kuò)展方法,如有不對,請多多指教!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI