question

92904252 avatar image
0 Votes"
92904252 asked 92904252 commented

How to BinarySearch Generic List in PowerShell

I would like to binarysort a generic list of pscustomobject, but I don't know how to write code for it.
Do anyone know how to write the code for binarysearching a pscustomobject list?

array of pscustomobject

$list1 =
[pscustomobject]@{Id = 5; Name = "Tom"},
[pscustomobject]@{Id = 1 ; Name = "Ben"},
[pscustomobject]@{Id = 8 ; Name = "Alice"},
[pscustomobject]@{Id = 4 ; Name = "Lucy"},
[pscustomobject]@{Id = 9 ; Name = "Sam"},
[pscustomobject]@{Id = 7 ; Name = "Bill"}

Generic List of pscustomobject

using namespace System.Collections.Generic;
$l1 = [List[PSCustomObject]]::new()
$list1 | % {$l1.add($_)}

Sort the list

$l1.Sort( { $args[0].name.compareto($args[1].name) })

The follwing code doesn't work...

PS> $l1.BinarySearch({$args.Name -eq "Ben"})

Error

MethodInvocationException: Exception calling "BinarySearch" with "1" argument(s): "Failed to compare two elements in the array."

windows-server-powershell
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

IanXue-MSFT avatar image
0 Votes"
IanXue-MSFT answered 92904252 commented

Hi,

The Array.BinarySearch method doesn't accept the -eq expression. You have to uses the IComparer interface
https://docs.microsoft.com/en-us/dotnet/api/system.array.binarysearch?view=net-5.0#System_Array_BinarySearch_System_Array_System_Object_System_Collections_IComparer_

The code could be like this

 Class ObjComparer : IComparer[System.Object] {
     [System.Object]$x
     [System.Object]$y
     [int]Compare($x,$y) {
         return [System.Collections.CaseInsensitiveComparer]::new().Compare($x.Name, $y)
     }
 }
 $l1.BinarySearch("Ben", [ObjComparer]::new())


Best Regards,
Ian Xue
============================================
If the Answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Great! Perfect answer. Thank you very much.

0 Votes 0 ·