Linq之DataTable:过滤【Select】

1、函数Convert(A, 'B'): 参数A:需要进行处理的结果,参数B:要转换成的类型,必须是C#能够识别的类型,例如System.Int32

2、目的:通过Select来过滤数据,在查询条件中需存在算术运算,需要对结果进行处理,(例如取整数)可以通过以上函数来进行处理 

3、实例:

  1)数据源:

public static class DataSource
    {
        public static DataTable GetDataSource()
        {
            DataTable dtSource = new DataTable();
            //实例化三个列
            DataColumn name = new DataColumn("name", System.Type.GetType("System.String"));
            DataColumn debittotal = new DataColumn("debittotal", System.Type.GetType("System.Decimal"));
            DataColumn lendtotal = new DataColumn("lendtotal", Type.GetType("System.Decimal"));
            DataColumn period = new DataColumn("period", Type.GetType("System.Int32"));
            dtSource.Columns.Add(name);
            dtSource.Columns.Add(debittotal);
            dtSource.Columns.Add(lendtotal);
            dtSource.Columns.Add(period);
            DataRow row = dtSource.NewRow();
            row["name"] = "A";
            row["debittotal"] = 12;
            row["lendtotal"] = 24;
            row["period"] = 202011;
            dtSource.Rows.Add(row);
            row = dtSource.NewRow();
            row["name"] = "B";
            row["debittotal"] = 23;
            row["lendtotal"] = 36;
            row["period"] = 202010;
            dtSource.Rows.Add(row);
            row = dtSource.NewRow();
            row["name"] = "C";
            row["debittotal"] = 34;
            row["lendtotal"] = 48;
            row["period"] = 202111;
            dtSource.Rows.Add(row);
            return dtSource;
        }
        
        public static void ShowDataTable(DataRow[] dt)
        {
            foreach (DataRow item in dt.AsEnumerable())
            {
                Console.WriteLine("{0}-{1}-{2}-{3}", item.Field<string>("name"), item.Field<decimal>("debittotal"), item.Field<decimal>("lendtotal"), item.Field<int>("period"));
            }
        }
    }
View Code

  2)客户端:

 static void Main(string[] args)
        {
             int openYear = 2020;
            DataTable dtSource = DataSource.GetDataSource();
            Console.WriteLine("----------------数据源----------------");
            DataSource.ShowDataTable(dtSource.AsEnumerable().ToArray());
            Console.WriteLine("----------------查询期间是本年的数据【A】----------------");
            DataRow[] drs = dtSource.Select(string.Format("period /100  = {0}", openYear));
            DataSource.ShowDataTable(drs);
            Console.WriteLine("----------------查询期间是本年的数据【B】----------------");
            drs = dtSource.Select(string.Format("Convert(period /100, 'System.Int32')  = {0}", openYear));
            DataSource.ShowDataTable(drs);
            Console.ReadKey();
        }
View Code

  3)结果展示:

  

 

 

 

 

写写博客,方便自己也方便需要的人~~

posted @ 2020-12-01 16:44  会编程的厨子  阅读(419)  评论(0编辑  收藏  举报