DataTable 根据某一列的个数进行排序+多条件排序

前言:

dataTable对多条件排序,举个例子

可以在每一步自己打断点看下dt的状态,

    dt.DefaultView.Sort = dt.Columns[2].ColumnName + " DESC," + dt.Columns[1].ColumnName + " DESC" ; 

   dt = dt.DefaultView.ToTable();

   可以实现进行多条件排序

public static void Get()
        { 
            DataTable dt = new DataTable();
            dt.Columns.Add("Name");
            dt.Columns.Add("Age"); 
            dt.Columns.Add("count");   //增加一列
            dt.Rows.Add("小明", 21);
            dt.Rows.Add("小明", 10);
            dt.Rows.Add("小红", 91);
            dt.Rows.Add("小红", 7);
            dt.Rows.Add("小美", 3);
            dt.Rows.Add("小章", 3);
            dt.Rows.Add("小章", 3);
            dt.Rows.Add("小章", 6);
            dt.Rows.Add("小章", 3);
            dt.Rows.Add("小章", 3);
            dt.Rows.Add("小章", 3);  
            List<string> str = new List<string>();
            for (int i = 0; i < dt.Rows.Count; i++)
            { 
                str.Add(dt.Rows[i][0].ToString());
            }
            //计算字典数量 
            Dictionary<string, int> dic = new Dictionary<string, int>();
            for (int i = 0; i < str.Count; i++)
            {
                if (dic.ContainsKey(str[i]))
                {
                    dic[str[i]]++;
                }
                else
                {
                    dic[str[i]] = 1;
                }
            }
            
            for (int i = 0; i < dt.Rows.Count; i++) {
                if (dic.ContainsKey(dt.Rows[i]["Name"].ToString()))
                {
                    dt.Rows[i]["count"] = dic[dt.Rows[i]["Name"].ToString()];
                } 
            }

            dt.DefaultView.Sort = dt.Columns[2].ColumnName + " DESC," + dt.Columns[1].ColumnName + " DESC" ;
            dt = dt.DefaultView.ToTable();

            
            //dt.DefaultView.Sort = dt.Columns[7].ColumnName + " DESC," + dt.Columns[3].ColumnName + " DESC," + dt.Columns[5].ColumnName + " DESC,"   + dt.Columns[6].ColumnName + " ASC";



            foreach (DataRow s in dt.Rows)
            {
                Console.WriteLine(s[0].ToString() + "--" + s[1].ToString() + "<br/>");
            }
            Console.ReadKey();
            dt = dt.DefaultView.ToTable();



            var result3 = from pair in dic orderby pair.Value descending select pair;
            foreach (KeyValuePair<string, int> pair in result3)
            {
                Console.WriteLine(pair.Key.ToString() + " " + pair.Value.ToString());
            }
            Console.Read();
            dt.Columns.Add("sort");

            dt = dt.DefaultView.ToTable();
            Console.ReadKey();




           
        }

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页