2013-07-14 58 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()