Home > database >  reorder datatable rows with a specific sequence of values
reorder datatable rows with a specific sequence of values

Time:01-08

I have a datatable that looks like this:

IDDOC   DOCNAME
1       mydoc1
153     mydoc2
98      mydoc3  
1327    mydoc4
241     mydoc5  

I would like to find a way to reorder the rows in that datatable by basing on a specific sequence of ID

For example, with a sequence like this : 1327,98,1 the expected output would be :

IDDOC   DOCNAME
1327    mydoc4
98      mydoc3  
1       mydoc1
153     mydoc2 (not in my sequence so this row comes at the end)
241     mydoc5 (not in my sequence so this row comes at the end)

I was thinking about creating a new empty database and adding the row with the IDDOC coming first, then second, then third in the sequence, then finally all the rows not present in my sequence but i was wondering if something cleaner already existed. Thank you a lot for your help!

CodePudding user response:

You could use this approach:

dt = dt.AsEnumerable()
    .OrderBy(r => r.Field<int>("IDDOC") == 1327 ? 0 : 1)
    .ThenBy(r => r.Field<int>("IDDOC") == 98 ? 0 : 1)
    .ThenBy(r => r.Field<int>("IDDOC") == 1 ? 0 : 1)
    .CopyToDataTable();

If you want a dynamic list of id's and the DataTable should be ordered by this sequence:

List<int> docIdSequence = new List<int>{ 1327, 98, 1 };

dt = dt.AsEnumerable()
    .OrderBy(r => { 
        int ix = docIdSequence.IndexOf(r.Field<int>("IDDOC"));
        return ix >= 0 ? ix : int.MaxValue;
    })
    .CopyToDataTable();

Note that CopyToDataTable throws an exception if there are no input DataRows. So you have to check if dt.Rows.Count > 0 before you use above code.

  •  Tags:  
  • Related