在数据表中对项目进行排序。

5

我有一个数据表,其中只有一列包含姓名。我想将下拉框与数据表一起加载,使得姓名按字母顺序排列,例如:以a开头的名字排在第一个,以b开头的名字排在第二个。我该如何对数据表进行排序?有人能帮忙吗?

5个回答

14

使用DataView:

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

非常简单,这是一个很好的解决方案。 - rlee923
我认为应该使用DataRowView而不是DataRow: foreach(DataRowView dr in dv) - TTT

4

方法一

    // 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()

方法二: 如果使用数据集(DataSets)

    DataTable datatable = dataSet.Tables["yourDataTable"];    
    DataView view = datatable .AsDataView();

    view.Sort = "FirstName desc, LastName desc";

    combobox.DataSource = view;
    combobox.DataBind();

参考资料: 使用DataView进行排序(LINQ to DataSet)


3
这里是你正在寻找的答案。 点击此处 查看答案。
DataTable MyDataTable;
const string SortByClause = "[SomeCol] ASC";
MyDataTable.DefaultView.Sort = SortByClause ;


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;


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接