Not working for contains Customr sort satatable

Continuing the discussion from How to use custom sort in Data Table:

Hi @ppr , I used your method to sort customly but the value must be exact match with the cell value then only its getting sorted. I need a contains instead of exact match sorting …

i have created a custom sort order
image

the input

Hi,

How about the following sample?

dt.AsEnumerable.OrderBy(Function(r) Convert.ToInt32(dict.Where(Function(kv) r(0).ToString.StartsWith(kv.Key)).FirstOrDefault().Value)).CopyToDataTable()

Sample20231124-11L.zip (7.8 KB)

Regards,

Can u explain where is the column name called … etc …

HI,

Can you try to modify r(0) to r(“ColumnName”) as the following?

dt.AsEnumerable.OrderBy(Function(r) Convert.ToInt32(dict.Where(Function(kv) r("ColumnName").ToString.StartsWith(kv.Key)).FirstOrDefault().Value)).CopyToDataTable()

Regards,

ok cool… got it!!

Instead of startwith function can we use Contains functionality.??

because for example am having a value like “ABC canada ,AVC canada,AVS georgia”

Here this wont work

Hi,

Yes. However, please note that if there are multiple matched keywords, the first matched string in the dictionary will reflect the result.

Regards,

have a look at this modification:

dtDataOrdered =

(From d In dtData.AsEnumerable
Let cv = d("YourColName").toString.Trim
Let dk = dictSortOrder.Keys.First(Function (k) cv.Contains(k))
Order By dictSortOrder(dk)
Select r = d).CopyToDataTable

hi @Yoichi

there is one issue here. where for example find my input DT below

Input dt
Mid_ALias
Mobile
CC
WFG
Cri
AMX
XHS

And in my sort DT only i have mentioned known mids like Mobile1 CC2 WFG3

There will be lot of unidentified mids soo while sorting this unidentified are coming first and then the sorted are coming

not working if the mentioned Mid not present in the input dt

image

in sort dt
Mobile
CC
WFG

but in input

AMX
Mobile
WFG
only there so CC is not there in input thats why its throwing error

HI,
How about the following sample?

dt.AsEnumerable.OrderBy(Function(r) if(dict.Where(Function(kv) r(0).ToString.StartsWith(kv.Key)).Any, Convert.ToInt32(dict.Where(Function(kv) r(0).ToString.StartsWith(kv.Key)).First().Value),Int32.MaxValue)).CopyToDataTable()

Sample20231124-11Lv3.zip (3.1 KB)

Regards,

Details are not derivable and the exact error message could help us further

A missing one in the SortDT can throw an exception, which we could also make more defensive.

A missing partial value in the InputDT would not trigger an error