0

In Powershell, I can do the following with a list

$obj = New-Object System.Object    
foreach ($item in $list) {
       $obj | Add-Member -type NoteProperty -name fname -value $item.firstname
       $obj | Add-Member -type NoteProperty -name lname -value $item.lastname
    }

    $obj

and this will print out two columns with the first and last name.

In C#, i'm not sure how I can accomplish this. Do I need to create a custom class for each object? Or is there a way to do this dynamically in c# like in powershell?

The data i've got is in JSON. I can use JSON.net to iterate through the list of results but I'm not sure how to put them into an object such that

WriteObject(customObj);

will result in the same output as above.

By the way, this is all inside of a PSCmdlet class so output will always go to the console/cmd window.

thank you.

anoopb
  • 533
  • 4
  • 6
  • 20

2 Answers2

4

Your best option would be to use anonymous types. The code you gave would (probably) be equivalent to:

var obj = new List<dynamic>();
foreach (var item in list)
    obj.Add(new { fname = item.firstname, lname = item.lastname });
//From here, use whatever output method you would like.

To access the members, use obj[index].fname to get the fname at index, obj[index].lname to get the lname at index, obj.Select(item => item.fname) to get an IEnumerable<string> of all fnames, and obj.Select(item => item.lname) to get an IEnumerable<string> of all lnames.

LegionMammal978
  • 680
  • 8
  • 15
4

In C# you should operate on PSObject to achieve same result as your PowerShell code:

PSObject obj=new PSObject();
obj.Properties.Add(new PSNoteProperty(fname,item.firstname));
obj.Properties.Add(new PSNoteProperty(lname,item.lastname));
WriteObject(obj);
user4003407
  • 21,204
  • 4
  • 50
  • 60
  • Sorry it took so long for me to verify your answer. I was only just able to get back to the task. I followed your suggestion along with ArrayList to produce a nice table of objects that can be easily used by PowerShell. Thanks again. – anoopb Jan 22 '15 at 22:10