c#之DataTable的扩展方法

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

目前创新互联已为1000多家的企业提供了网站建设、域名、网页空间、网站托管、服务器托管、企业网站设计、宁德网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。

    由于公司中的项目大量的使用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写的几个扩展方法,如有不对,请多多指教!

网页标题:c#之DataTable的扩展方法
文章位置:https://www.cdcxhl.com/article8/jocjop.html

成都网站建设公司_创新互联,为您提供外贸建站软件开发营销型网站建设企业建站网站策划网站营销

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都网页设计公司