1

I have a datatable,

PId     PName   Qty
123     XYZ     2
223     ABC     4
434     PQR    33      

I want to sort it on "PName" but not asc/ desc order, If I pass PName as "PQR", then PQR should come first and then rest of the rows, same if I pass "ABC" then "ABC" should come first and then rest of the rows. Basically wants to reshuffle the rows where first row should be the "PName" which I am holding in a variable.

Thanks

Desired output If I have "ABC", then the above datatable should reshuffle as,

PId     PName   Qty
223     ABC     4
123     XYZ     2
434     PQR    33

If I have "PQR", then the above datatable should reshuffle as,

PId     PName   Qty
434     PQR    33   
123     XYZ     2
223     ABC     4
Johny Bravo
  • 414
  • 9
  • 34
  • Can you use linq? – D Mishra Nov 12 '16 at 07:05
  • yes. Can you please show me how it will work? – Johny Bravo Nov 12 '16 at 07:06
  • Refer my answer, as any clarification needed. – D Mishra Nov 12 '16 at 07:13
  • If you don't want to rebuild the table I suggest using a `DataView` and setting its `Sort` property to the appropriate expression based on a calculated column in your datatable https://msdn.microsoft.com/en-us/library/system.data.dataview(v=vs.110).aspx something like this answer http://stackoverflow.com/a/583943/491907 – pinkfloydx33 Nov 12 '16 at 09:38

2 Answers2

2
    DataTable dt = new DataTable();
    dt.Columns.Add("PId", typeof(Int32));
    dt.Columns.Add("PName", typeof(string));
    dt.Columns.Add("Qty", typeof(Int32));
    dt.Rows.Add(123, "XYZ", 2);
    dt.Rows.Add(223, "ABC", 4);
    dt.Rows.Add(434, "PQR", 33);

    var stkLists = dt.AsEnumerable().ToList();
    var matchList = stkLists.Where(m => m["PName"].ToString().StartsWith("PQR")).ToList();
    var FinalList = matchList.Concat(stkLists.Except(matchList).ToList());
D Mishra
  • 1,518
  • 1
  • 13
  • 17
  • "Your complete table in list form", do I need to complete y datatable to list? – Johny Bravo Nov 12 '16 at 07:20
  • Yes in list form, This will give you desired output and will not sort entire table. – D Mishra Nov 12 '16 at 07:21
  • List stkLists = dtStk.AsEnumerable().ToList(); var stkList = stkLists; var matchList = stkList.Where(m => m.PName.StartsWith(batchId)).ToList(); var FinalList = matchList.Concat(stkList.Except(matchList).ToList()); – Johny Bravo Nov 12 '16 at 07:30
  • m.PName shows DataRow doesnot contain a definition for "PName" and no extension method... – Johny Bravo Nov 12 '16 at 07:31
1

Try like this:

DataTable dt = new DataTable();
dt.Columns.Add("PId", typeof(Int32));
dt.Columns.Add("PName", typeof(string));
dt.Columns.Add("Qty", typeof(Int32));
dt.Rows.Add(123, "XYZ", 2);
dt.Rows.Add(223, "ABC", 4);
dt.Rows.Add(434, "PQR", 33);



string Name = "PQR";
DataTable newDt = dt.Rows.Cast<DataRow>().Where(r => r.ItemArray[1] == Name).CopyToDataTable();
dt = dt.Rows.Cast<DataRow>().Where(r => r.ItemArray[1] != Name).CopyToDataTable();
newDt.Merge(dt);
James
  • 729
  • 6
  • 10