温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

c# 之DataTable的扩展方法

发布时间:2020-05-19 17:07:23 来源:网络 阅读:1210 作者:SmallHan 栏目:编程语言

    由于太懒了,很久没更新了。毕业了,得好好装逼学习了,不能一心想着完了。

    由于公司中的项目大量的使用DataTable,而每次对datatable进行操作的时候需要写很多相同的代码,所以秉着 装逼而学习 的态度,于是撸了几个扩展方法,记录下来,学习下。

    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中的每条记录执行某个操作
        /// </summary>
        /// <param name="table">DataTable</param>
        /// <param name="func">Func委托</param>
        static void ForEach(Program program)
        {
            Console.WriteLine("给DataTable中的每条记录执行某个操作");
            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">字段的数据类型</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">给定字段的数据类型</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>
        /// 添加指定的列并且附默认值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <param name="columnFiled"></param>
        /// <param name="value"></param>
        static void AddColumnFiledTwo(Program program)
        {
            Console.WriteLine("添加指定的列并且附默认值");
            ExMethod.AddColumnFiled<string>(program.LinqTable, "job", "码农");
            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 录入数据
        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
    }

以下是扩展方法

  public static class ExMethod
    {
        /// <summary>
        ///  给DataTable中的每条记录执行某个操作
        /// </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>
        /// 添加指定的列并且附默认值
        /// </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写的几个扩展方法,如有不对,请多多指教!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI