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

时间:2010-02-19 05:05:17

标签: c#

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

5 个答案:

答案 0 :(得分:13)

使用DataView:

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

答案 1 :(得分:4)

方法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 :如果使用DataSet

    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)

答案 2 :(得分:3)

Here's the answer您正在寻找。

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

答案 3 :(得分:1)

答案 4 :(得分:0)

使用类型化数据集 在精确数据类型中创建数据表 例如,我创建了一个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已排序                 return dsAppointment;