Johny Bravo Johny Bravo - 26 days ago 4
C# Question

Sort datatable based on value in the column

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

Answer
    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());