How to BinarySearch Generic List in PowerShell

芹沢 基樹 111 Reputation points
2020-12-15T07:25:20.563+00:00

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
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,602 questions
0 comments No comments
{count} votes

Accepted answer
  1. Ian Xue 38,936 Reputation points Microsoft Vendor
    2020-12-16T09:49:20.8+00:00

    Hi,

    The Array.BinarySearch method doesn't accept the -eq expression. You have to uses the IComparer interface
    https://learn.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.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.