2

I have a DataTable that must be sorted, however i want to return a particular row as the last row even after sorting the DataTable. I will identify this row by a string value in a partiucular column.

  public DataTable StandardReport3B(string missionId, string reportType, string startDate, string endDate)
    {
        List<long> missionIdList = new List<long>();
        string[] missionIds = missionId.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

        foreach (string mission in missionIds)
        {
            missionIdList.Add(Convert.ToInt64(mission));
        }

        DataTable dt = new DataTable();
        object reportData = null;

        using (var ctx = new MedicalServiceEntities())
        {
            reportData = ctx.GetData(startDate, endDate, missionId).ToList();
        }

        dt = this.GenericListToDataTable(reportData);

        DataView dv = dt.DefaultView;
        dv.Sort = dt.Columns[0].ColumnName + " Asc";
        return dv.ToTable();
    }
leppie
  • 115,091
  • 17
  • 196
  • 297
StackTrace
  • 9,190
  • 36
  • 114
  • 202

2 Answers2

5

You can use LINQ-to-DataSet:

dt = dt.AsEnumerable()
    .OrderBy(r => r.Field<string>(0) == "Special Value")
    .ThenBy(r => r.Field<string>(0))
    .CopyToDataTable();

That works because the comparison returns either true or false and false is "lower".


In case someone just wants to know how to move the row in the table to another index as the title suggests: Add data row to datatable at predefined index

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

I will identify this row by a string value in a partiucular column.

What about:

dv.Sort = "ParticularColumn ASC, " + dt.Columns[0].ColumnName + " ASC">

Where "ParticularColumn" is a column with an identical, low value for all rows except the one you want to be last - and this row has a higher value.

Joe
  • 122,218
  • 32
  • 205
  • 338