views:

69

answers:

2
add-type -Language CSharpVersion3 -TypeDefinition @"
    public class pack_code
    {
        public pack_code() {}

        public string code { get; set; }
        public string type { get; set; }
    }
"@

$a = New-Object pack_code
$a.code = "3"
$a.type = "5"
$b = New-Object pack_code
$b.code = "2"
$b.type = "5"
$c = New-Object pack_code
$c.code = "2"
$c.type = "5"
$d = New-Object pack_code
$d.code = "1"
$d.type = "1"

$codes = New-Object 'System.Collections.Generic.List[object]'
$codes.add($a)
$codes.add($b)
$codes.add($c)
$codes.add($d)

is there a way to select distinct from $codes and select the objects where type equals 1? How can i use linq with PowerShell?

+2  A: 

For distinct use the Select-Object cmdlet (aliased to Select) with the Unique parameter e.g.:

PS> 1,2,3,4,4,2 | Select-Object -Unique
1
2
3
4

For filtering use the Where-Object cmdlet (aliased to Where and ?):

PS> $codes | where {$_.Type -eq '1'}

As for LINQ, you can't use LINQ operators in PowerShell because PowerShell doesn't support calling generic .NET methods or static extension methods which are both crucial to LINQ.

Keith Hill
+1  A: 

What Keith said. Plus, changed the constructor in your C# and used the -Unique parameter on the Sort cmdlet.

Add-Type -Language CSharpVersion3 -TypeDefinition @"
    public class pack_code
    {
        public pack_code(string code, string type) {
            this.code=code;
            this.type=type;
        }

        public string code { get; set; }
        public string type { get; set; }
    }
"@

$codes = New-Object 'System.Collections.Generic.List[object]'
$codes.Add( ( New-Object pack_code(3, 5) ))
$codes.Add( ( New-Object pack_code(2, 5) ))
$codes.Add( ( New-Object pack_code(2, 5) ))
$codes.Add( ( New-Object pack_code(1, 1) ))
$codes.Add( ( New-Object pack_code(2, 2) ))
$codes.Add( ( New-Object pack_code(2, 1) ))
$codes.Add( ( New-Object pack_code(2, 1) ))

$codes | sort code, type -Unique | where {$_.type -eq 1}
Doug Finke