对数据表中的项目进行排序

问题描述:

我有一个数据表,其中一列包含names.I想要使用数据表加载组合框,使得名称应该按字母顺序排列,例如:名字以a开头。 第二个名字以b开头。我可以如何对datatable中的数据进行排序。任何人都可以帮忙吗?对数据表中的项目进行排序

使用一个DataView:

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

非常简单,这样一个不错的解决方案。 – rlee923 2012-01-04 09:44:42

+0

我认为这应该是DataRowView而不是DataRow: foreach(DataRowView dr in dv) – TTT 2012-10-17 22:34:34

方法1

// 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:如果使用数据集

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)

Here's the answer你在找。

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

使用类型数据集 创建在precising类型例如数据 的数据表中我有创建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;