热门IT资讯网

c# 之DataTable的扩展方法

发表于:2024-11-29 作者:热门IT资讯网编辑
编辑最后更新 2024年11月29日,由于太懒了,很久没更新了。毕业了,得好好装逼学习了,不能一心想着完了。由于公司中的项目大量的使用DataTable,而每次对datatable进行操作的时候需要写很多相同的代码,所以秉着 装逼而学习

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

由于公司中的项目大量的使用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();        }        ///         /// 给DataTable中的每条记录执行某个操作        ///         /// DataTable        /// Func委托        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();        }        ///         /// 从DataTable中获取某个字段组成的集合        ///         /// 字段的数据类型        /// DataTable        /// Func委托        /// IEnumerable        static void Select(Program program)        {            Console.WriteLine("从DataTable中获取某个字段组成的集合");            List list = (List)ExMethod.Select(program.LinqTable, "id");            foreach (var it in list)            {                Console.WriteLine(it);            }            Console.WriteLine();        }        ///         /// 获取DataTable中某个字段符合给定条件的处理过的集合        ///         ///         ///         ///         ///         ///         static void SelectOne(Program program)        {            Console.WriteLine("获取DataTable中某个字段符合给定条件的处理过的集合");            List list = (List)ExMethod.Select(program.LinqTable, "id", (int x) =>            {                return x + 10;            });            foreach (var it in list)            {                Console.WriteLine(it);            }            Console.WriteLine();        }        ///         /// 判断给定DataTable中是否存在某个字段值符合给定条件的记录        ///         /// 给定字段的数据类型        /// DataTable        /// 字段名称        /// Func委托        /// True/False        static void Contains(Program program)        {            Console.WriteLine("判断给定DataTable中是否存在某个字段值符合给定条件的记录");            bool flg = ExMethod.Contains(program.LinqTable, "name", (string name) =>            {                return name.Equals("1 Max");            });            Console.WriteLine(flg.ToString());            Console.WriteLine();        }        ///         /// 获取DataTable中符合某个条件的唯一记录        ///         /// DataTable        /// Func委托        ///         static void SingleOrDefault(Program program)        {            Console.WriteLine("获取DataTable中符合某个条件的唯一记录");            DataRow row = ExMethod.SingleOrDefault(program.LinqTable, "id", (int i) =>            {                return i == 10;            });            if (row != null)            {                foreach (var it in row.ItemArray)                {                    Console.Write(it + " ");                }                Console.WriteLine();            }            Console.WriteLine();        }        ///         /// 添加指定的列        ///         ///         ///         ///         static void AddColumnFiled(Program program)        {            Console.WriteLine("添加指定的列");            ExMethod.AddColumnFiled(program.LinqTable, "sex");            Console.WriteLine(program.LinqTable.Columns.Count);            Console.WriteLine();        }        ///         /// 添加指定的列并且附默认值        ///         ///         ///         ///         ///         static void AddColumnFiledTwo(Program program)        {            Console.WriteLine("添加指定的列并且附默认值");            ExMethod.AddColumnFiled(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();        }        ///         ///  DataTable中某个字段具有最大值的记录        ///         ///         static void Max(Program program)        {            Console.WriteLine("DataTable中某个字段具有最大值的记录");            DataRow row = ExMethod.Max(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    {        ///         ///  给DataTable中的每条记录执行某个操作        ///         ///         ///         public static void ForEach(this DataTable table, Action action)        {            for (int i = 0; i < table.Rows.Count; i++)            {                DataRow current = table.Rows[i];                action(current);            }        }        ///         /// 从DataTable中获取某个字段组成的集合        ///         ///         ///         ///         ///         public static IEnumerable Select(this DataTable dt, string name)        {            DataColumnCollection columns = dt.Columns;            IList iList = new List(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;        }        ///         ///  获取DataTable中某个字段符合给定条件的处理过的集合        ///         ///         ///         ///         ///         ///         public static IEnumerable Select(this DataTable dt, string name, Func func)        {            DataColumnCollection columns = dt.Columns;            IList iList = new List();            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;        }        ///         /// 判断给定DataTable中是否存在某个字段值符合给定条件的记录        ///         ///         ///         ///         ///         ///         public static bool Contains(this DataTable dt, string name, Func 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;        }        ///         /// 获取DataTable中符合某个条件的唯一记录        ///         ///         ///         ///         ///         ///         public static DataRow SingleOrDefault(this DataTable dt, string name, Func 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;        }        ///         /// 添加指定的列        ///         ///         ///         ///         public static void AddColumnFiled(this DataTable dt, string columnFiled)        {            if (!string.IsNullOrWhiteSpace(columnFiled))            {                dt.Columns.Add(columnFiled, typeof(T));            }        }        ///         /// 添加指定的列并且附默认值        ///         ///         ///         ///         ///         public static void AddColumnFiled(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;                }            }        }        ///         /// DataTable中某个字段具有最大值的记录        ///         ///         ///         ///         ///         public static DataRow Max(this DataRowCollection collection, Func func)        {            string name = func();            DataTable dt = collection[0].Table;            DataColumnCollection columns = dt.Columns;            if (!columns.Contains(name)) return null;            Comparer comparer = Comparer.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写的几个扩展方法,如有不对,请多多指教!

0