开发者

Need help converting PHP to C# [closed]

开发者 https://www.devze.com 2023-02-14 19:03 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

I have this php code:

$lines = file("data.csv");
$nested = array();
$links = array();

// first, create a structure that contains the connections between elements
foreach ($lines as $line) {
  list($child, $parent) = explode(","开发者_运维知识库, $line);
  if (trim($child) == trim($parent)) {
    $nested[$parent] = null;
  } else {
    // add it to the children of parent
    $links[$parent][] = $child;
  }
}

function process(&$arr) {
  global $links;
  foreach ($arr as $key => $value) {
    // no more children => stop recursion
    if (!array_key_exists($key, $links)) {
      $array[$key] = null;
      continue;
    }
    // insert its children
    $arr[$key] = array_flip($links[$key]);
    // recurse down
    process($arr[$key]);
  }
}


function print_html($multi_dimensional_array)
{
    $m = $multi_dimensional_array;
    $keys = array();

    foreach($m as $key=>$value) {
            $keys[] = $key;
    }

    $i = 0;

    while($i < count($multi_dimensional_array)) {
        echo '<li><a href="#">'.$keys[$i].'</a>';
        if(is_array($multi_dimensional_array[$keys[$i]])) {
                echo '<ul>';
                print_html($multi_dimensional_array[$keys[$i]]);
                echo '</ul>';
        }
        echo '</li>';
        $i++;
    }
}

process($nested);

print_html($nested);

The data.csv format is (value,parent), an example would be:

one,one
two,two
three,three
sub_one,one
sub_one2,one
sub_two,two
sub_two2,two
sub_two3,two
sub_three,three
sub_sub_one,sub_one
sub_sub_one2,sub_one

Basically this what this PHP code does is create a multidimensional array that contains the parent name as key and the childs as values, and if a child also contains sub childs then it would be a key which contains subkeys, etc... and it will then print an html formatted list for that array.

How could I use C# to do what this php code does?


Arrays in C# aren't like arrays in PHP. You'll probably need to implement the Composite pattern to get the desired data structure. That's just a pointer to the right (I think) direction for a small part of your task. If you do end up using the pattern, consider Dictionary<string, TComposite> for the type of children collection.

0

精彩评论

暂无评论...
验证码 换一张
取 消