【问题标题】:Sort items in datatable对数据表中的项目进行排序
【发布时间】:2013-10-25 23:47:02
【问题描述】:

我有一个数据表,其中有一列包含名称。我想加载带有数据表的组合框,以便名称应按字母顺序排列,例如:名字以 a 开头。 第二个名字以 b 开头。如何对数据表中的数据进行排序。有人可以帮忙吗?

【问题讨论】:

    标签: c#


    【解决方案1】:

    使用数据视图:

    DataTable dt; //comes from somewhere...
    DataView dv = new DataView(dt)
    dv.Sort = "Name ASC";
    foreach(DataRowView drv in dv)
        //....
    

    【讨论】:

    • 非常简单,也是一个很好的解决方案。
    • 我认为应该是DataRowView而不是DataRow:foreach(DataRowView dr in dv)
    【解决方案2】:

    方法一

        // orderby "FistName" column
        EnumerableRowCollection<DataRow> query = 
                        from order in datatable.AsEnumerable()
                        orderby datatable.Field<string>("FirstName")
                        select datatable;
    
        DataView view = query.AsDataView();
    
        // bind to your combobox
        combobox.DataSource = view;
        combobox.DataBind()
    

    方法2:如果使用DataSets

        DataTable datatable = dataSet.Tables["yourDataTable"];    
        DataView view = datatable .AsDataView();
    
        view.Sort = "FirstName desc, LastName desc";
    
        combobox.DataSource = view;
        combobox.DataBind();
    

    参考:Sorting with DataView (LINQ to DataSet)

    【讨论】:

      【解决方案3】:

      Here's the answer 您正在寻找。

      DataTable MyDataTable;
      const string SortByClause = "[SomeCol] ASC";
      MyDataTable.DefaultView.Sort = SortByClause ;
      

      【讨论】:

        【解决方案4】:
        【解决方案5】:

        使用类型化数据集 在精确的数据类型中创建数据表 例如我创建了一个 dsAppointment

         DsAppointment dsAppointmentTmp = new DsAppointment();
         DsAppointment dsAppointment = new DsAppointment();
        //add all appointment
         dsAppointmentTmp.Appointment.AddAppointmentRow(name,start,end,body)
        //use select(filter,sort(name of columns)
        DataRow[] rows1 = dsAppointmentTmp.Tables[0].Select(string.Empty, dsAppointmentTmp.Tables[0].Columns[1].ToString());
        
                    foreach (DataRow thisRow in rows1)
                    {
                            dsAppointment.Tables[0].Rows.Add(thisRow.ItemArray);
        
                    }
        

        //返回排序后的dsAppointment 返回 dsAppointment;

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-25
          • 2011-04-09
          • 2012-02-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多