2013-07-14 56 views
2

我有一个dataTable,其中包含对应的名称和分数。我想根据分数降序排序。Sorting DataTable C#

这里是DB.cs代码:

public class DB 
    { 
     public DataTable GetData() 
     { 
      string spName = "GetTime"; 
      Connection.Open(); 

      SqlCommand command = new SqlCommand(spName, Connection); 
      command.CommandType = CommandType.StoredProcedure; 

      SqlDataReader reader = command.ExecuteReader(); 
      DataTable dt = new DataTable(); 
      dt.Columns.Add("Name"); 
      dt.Columns.Add("Time"); 

      while (reader.Read()) 
      { 
       DataRow dr = dt.NewRow(); 
       dr["Name"] = Convert.ToString(reader["name"]); 
       dr["Time"] = Convert.ToInt32(reader["timeScore"]); 
       dt.Rows.Add(dr); 
      } 
      Connection.Close(); 
      return dt; 
     } 
    } 

这是Form3.cs

public partial class Form3 : Form 
    { 
     private Form2 form2; 
     public Form3() 
     { 
      InitializeComponent(); 
      loadData(); 
     } 

     public void loadData() 
     { 
      form2 = new Form2(); 
      DataTable dt2 = form2.db.GetData(); 
      dgvScore.DataSource = dt2; 
     } 
    } 

我应该怎么做,没有任何comparer像Java中排序呢?我只想要一个简单的算法答案。 感谢您的赞赏帮助!

回答

10

你并不需要循环读者:

SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); 
DataTable dt = new DataTable(); 
dt.Load(dr); 

然后,你可以简单地排序的默认视图:

dt.DefaultView.Sort = "timeScore desc"; 
0

这是一种不雅不得不应对DataView当你想排序一个DataTable所以这里是一个真的简单而简洁的方式来排序一个DataTable实例。我不认为简洁性与语义清晰度有冲突,但如果您认为它很混乱,请发表评论。

dt = new DataView(dt, "", "timeScore DESC", 
        DataViewRowState.CurrentRows).ToTable()