简体   繁体   中英

Sorting DataTable C#

I have a dataTable that contains corresponding names and scores. I want to sort it descending based on the scores.

Here is the code in 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;
        }
    }

And this is on 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;
        }
    }

What should I do to sort it without any comparer like in Java? I just want a simple algorithm answer. Thank you for your appreciated help!

You don't need to loop over the reader:

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

Then you can simply sort the defaultView:

dt.DefaultView.Sort = "timeScore desc";

It's kind of inelegant to have to deal with a DataView when you want to sort a DataTable so here's a really simple and concise way to sort a DataTable instance . I don't think the brevity breaks with semantic clarity, but please comment if you think it's confusing.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM