如何将php脚本转换为c#

时间:2011-02-22 23:37:17

标签: c# php

<?php

$list = array(
    array(
        'id' => '1',
        'pid' => '2',
        'value' => 'Value Foo 1',
    ),
    array(
        'id' => '2',
        'pid' => '6',
        'value' => 'Value Foo 2',
    ),
    array(
        'id' => '3',
        'pid' => '5',
        'value' => 'Value Foo 3',
    ),
    array(
        'id' => '4',
        'pid' => '2',
        'value' => 'Value Foo 4',
    ),
    array(
        'id' => '5',
        'pid' => '0',
        'value' => 'Value Foo 5',
    ),
    array(
        'id' => '6',
        'pid' => '0',
        'value' => 'Value Foo 6',
    ),
    array(
        'id' => '7',
        'pid' => '6',
        'value' => 'Value Foo 7',
    ),
    array(
       'id' => '8',
       'pid' => '2',
       'value' => 'Value Foo 8',
    ),
    array(
        'id' => '9',
        'pid' => '5',
        'value' => 'Value Foo 9',
    ),
);

//
// Creating a lookup array
//
$lookup = array();
foreach( $list as $item )
{
    $item['children'] = array();
    $lookup[$item['id']] = $item;
}

//
// Now build tree.
//
$tree = array();
foreach( $lookup as $id => $foo )
{
    $item = &$lookup[$id];
    if( $item['pid'] == 0 )
    {
        $tree[$id] = &$item;
    }
    else if(isset($lookup[$item['pid']]))
    {
        $lookup[$item['pid']]['children'][$id] = &$item;
    }
    else
    {
        $tree['_orphans_'][$id] = &$item;
    }
}

print_r( $tree );
?>

这就是我在c#中所拥有的

    public class Thing { 
             public String _id; 
             public int Bar; 
             public string _pid; 
    }
          var items = new[] {
                 new Thing { _id = "item1", _pid = "root", Baz = "a" },
                 new Thing {_id = "item2", _pid = "item1", Baz= "b" },
                 new Thing { _id = "item3", _pid = "item1", Baz = "c" },
                 new Thing { _id = "item4", _pid = "item1", Baz = "d" },
                 new Thing { _id = "item5", _pid = "item1", Baz = "e" },
                 new Thing { _id = "item6", _pid = "item1", Baz = "f" }
              };
//Then I create a lookup 
ILookup<string, Thing> lookup = items.ToLookup(i => i._id); 

//here is when I want to create a condition for each item in lookup to search if the _pid is in //the lookup as an item _id

foreach (IGrouping<string, Thing> item in lookup){ 

//here I dont know how to add a children object to the parent item and add a reference to the //current item 
//this is how Iam doing in php 
if(isset($lookup[$item['_pid']])) { 
$lookup[$item['_pid']]['children'][_id] = &$item; //<-item is passed by reference 
}

谢谢.. 问候

1 个答案:

答案 0 :(得分:0)

除非你知道你在做什么,否则最好使用真实对象而不是匿名对象!