Custom Sort a Datatable using linq

Hi Everyone,

My Requirement is i have an excel and i need to first group them according a column and then sort them , i have grouped them and getting a list of datatable and later using for each for list of datatable

Now i need to sort them based on custom sort and then normal sort for another column i.e., sort within a sort

*First need to custom sort based on the attachted list

Custom sort list

Within that sort based on Name column in ascending order

Output Required

Then delete designation column and merge name and location column headers and rename as Years(based on grouping done)

Any suggestions @Yoichi @ppr @Palaniyappan

Thanks in advance

Hi,

Hope the following helps you.

dictOrder = dtSortList.AsEnumerable.ToDictionary(Function(r) r(0).ToString(),Function(r) dtSortList.Rows.IndexOf(r))

dt = dt.AsEnumerable.OrderBy(Function(r) dictOrder(r("Designation").ToString)).CopyToDataTable()

Sample20220702-1.zip (12.6 KB)

Regards,

1 Like

@Yoichi thankyou it worked!!!

But @Yoichi one problem if there are values which are not present in that custom sort list then its throwing error

Hi,

If value isn’t in sort list, how do you want to handle it, first or last etc.

Regards,

@yoichi at last!! least priority

Hi,

Can you try the following expression?

dt.AsEnumerable.OrderBy(Function(r) if(dictOrder.ContainsKey(r("Designation").ToString),dictOrder(r("Designation").ToString),int32.MaxValue)).CopyToDataTable()

Regards,

@yoichi it worked thanks sir!!

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.