0

I am trying to sort my records out in the jQuery jTable but it is not sorting the records. I am getting records from an excel file.

Here's the sorting bit of the code that I am trying to sort the records:

if (sorting != null)
{
 daa.OrderByDescending(i => i.Date);
}

Here's my full code for your inspection:

public JsonResult TopPlayedInVenueList1(string sorting, string StartDate = "", string EndDate = "", int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
    {
        try
        {

            if (Request.IsAuthenticated == true)
            {
                string Path = @"C:\\5Newwithdate-1k.xls";
                OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" + Path + "';Extended Properties=" + (char)34 + "Excel 8.0;IMEX=1;" + (char)34 + "");
                OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);
                con.Close();
                System.Data.DataTable data = new System.Data.DataTable();
                da.Fill(data);

                List<TopPlayed> daa = new List<TopPlayed>();

                foreach (DataRow p in data.Rows)
                {
                    TopPlayed top = new TopPlayed()
                    {
                        TrackID = Convert.ToInt32(p.Field<double>("TrackID")),
                        Date = p.Field<DateTime>("DateTimes"),
                        TrackName = p.Field<string>("TrackName"),
                        ArtistName = p.Field<string>("ArtistName"),
                        Times = Convert.ToInt32(p.Field<double>("Times"))
                    };
                    daa.Add(top);
                }

                var listOrder = daa.Where(i => i.Date >= Convert.ToDateTime(StartDate) && i.Date <= Convert.ToDateTime(EndDate)).ToList();

                var newlist = listOrder.ToList().GetRange(jtStartIndex, jtPageSize);
                if (!string.IsNullOrWhiteSpace(sorting))
                {
                    newlist = listOrder.OrderByDescending(i => i.Date);
                }

                return Json(new { Result = "OK", Records = newlist, TotalRecordCount = listOrder.ToList().Count });

Before posting, I tried this and this examples but none of them worked.

To clarify, I am getting data from an excel file so that makes the List IEnumerable and not IQueryable right? Could you please kindly help out on this sorting issue. Thanks in advance.

Edit: Here's the updated code; Konrad

  if (sorting != null)
  {
    daa.OrderBy(i => i.Date);
  }
    var result = daa.OrderBy(i => i.Date);
Community
  • 1
  • 1
pv619
  • 409
  • 11
  • 29

2 Answers2

2

This call:

daa.OrderBy(i => i.Date);

do not sort data in-place, you must save results into another variable:

var result = daa.OrderBy(i => i.Date);
Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58
  • thanks - I tried what you suggested but it didn't work. I have updated my post with your code. – pv619 Apr 11 '14 at 11:25
  • Should it be something like `if (sorting != null){ daa = daa.OrderBy(i => i.Date); }` ? – Konrad Kokosa Apr 11 '14 at 11:27
  • I have already defined the `daa` `List` variable at the top so it won't take it. By default it sorts the table out (ASC / DESC) which is great but when clicked the table headers to sort the columns, then it's not doing anything. – pv619 Apr 11 '14 at 11:32
1

What you're doing in your code needs a bit of attention:

public JsonResult TopPlayedInVenueList1(string sorting, string StartDate = "", string EndDate = "", int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
{
    try
    {

        if (Request.IsAuthenticated == true)
        {
            string Path = @"C:\\5Newwithdate-1k.xls";
            OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" + Path + "';Extended Properties=" + (char)34 + "Excel 8.0;IMEX=1;" + (char)34 + "");
            OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);
            con.Close();
            System.Data.DataTable data = new System.Data.DataTable();
            da.Fill(data);

            List<TopPlayed> daa = new List<TopPlayed>();

            foreach (DataRow p in data.Rows)
            {
                TopPlayed top = new TopPlayed()
                {
                    TrackID = Convert.ToInt32(p.Field<double>("TrackID")),
                    Date = p.Field<DateTime>("DateTimes"),
                    TrackName = p.Field<string>("TrackName"),
                    ArtistName = p.Field<string>("ArtistName"),
                    Times = Convert.ToInt32(p.Field<double>("Times"))
                };

                //Don't sort inside your foreach!
                //if (sorting != null)
                //{
                //    daa.OrderBy(i => i.Date);
                //}

                daa.Add(top);
            }

            //var listOrder = daa.OrderBy(i => i.Date).ToList().Where(i => i.Date >= Convert.ToDateTime(StartDate) && i.Date <= Convert.ToDateTime(EndDate));
            //Don't run a Where after Orderby, probably you're fine...but not sure its guaruanteed, oh and you probably don't want to sort here either
            //I'm also a little surprised that the Convert statements in there aren't causing runtime errors..
            var listOrder = daa.Where(I => i.Date >= Convert.ToDateTime(StartDate) && i.Date <= Convert.ToDateTime(EndDate)).ToList();

            //you don't need to convert .ToList() to get .Count
            if (jtStartIndex + 150 > listOrder.ToList().Count)
            {
                int val = listOrder.ToList().Count - jtStartIndex;
                jtPageSize = val;
            }

            //This is the list that you actually return. This is where you sort your list
            var newlist = listOrder.OrderBy(i => i.Date).ToList().GetRange(jtStartIndex, jtPageSize);
            return Json(new { Result = "OK", Records = newlist, TotalRecordCount = listOrder.ToList().Count });

If I had to guess, your problem is that you're sorting in about four different places, and your sort is working, but you're just re-sorting it at the end so you think it's not working. Sort in only one location. If it's still not working, just put a breakpoint there and check the list yourself and see if it's sorting or not. Should be fairly easy to figure out.

It's a little hard to figure out from your code, but at the very bottom, this seems to be what you want (Not sure at this point if you want to order by descending or ascending, this is descending):

var newlist = listOrder.ToList().GetRange(jtStartIndex, jtPageSize);
if(!string.IsNullOrWhiteSpace(sorting))
{
  newlist = newlist.OrderByDescending(o => o.Date).ToList();
}

I'd take a moment to go through and make sure that you actually need all those ToList()'s in there also. Some look...unnecessary? Anyway, hopefully this helps you get your problem sorted out. Good Luck.

Mike C.
  • 3,024
  • 2
  • 21
  • 18
  • first of all thank you for taking your time out in with the code and helping me out. Your code made much more sense and made it easier to understand as I am fairly new with C#. I tried your code but it gives me out the following error `An explicit conversion already exists` on this line `newlist = listOrder.OrderByDescending(i => i.Date);` I have updated my code above in the post with your code for your inspection and thanks a million times again :) – pv619 Apr 11 '14 at 12:52
  • Also @Mike, I get the rows sorted by default which is great.. but when I click the table headers then it doesn't sort the columns. I get sorting arrows going up and down when clicked but the data stays the same.. and thanks again for your time, effort and help :) – pv619 Apr 11 '14 at 13:04
  • Right, I haven't tested this code. I'm guessing (and this is sorta funny) that you need to add .ToList() onto the end. I'll update my post with that. – Mike C. Apr 11 '14 at 13:04
  • Your second comment is harder to figure out. Step 1 is to verify that this function is returning your list in the order that you want. If that's true, then the problem isn't here, but in your view. – Mike C. Apr 11 '14 at 13:06
  • Sorry about that for not being clear, I was able to sort the columns but it was the headers sorting that is not working. Sorry again about the confusion. – pv619 Apr 11 '14 at 13:12
  • If this function is returning the list in the order that you want, then it sounds like the problem is in your view. We'd need to see that to be able to help figure it out. You can append that to this question, but if it were me I'd start a new question as that's really a separate issue from what was originally described. – Mike C. Apr 11 '14 at 13:15
  • Yes you're right @Mike and thanks for your help again :) made soo many things clear. I have created a new question [here](http://stackoverflow.com/questions/23014076/cannot-sort-table-headers-by-ascending-or-descending) and provided all the right information.. and sorry once again for the confusion :) – pv619 Apr 11 '14 at 13:36