¿Cómo puedo convertir este texto el contenido del archivo en una colección de objetos recursiva que pueda unirse a un TreeView? es decir, quiero terminar con una colección de objetos , el primero llamado países que tiene una colección de tres objetos secundarios: Francia, alemania, Italia, y así sucesivamente ...¿Cómo puedo convertir una lista de esquema de archivo de texto en una colección recursiva de objetos?
RESPUESTA: gracias a todos los que ayudaron en esto, aquí es mi código que analiza con éxito este esquema de texto en un árbol XAML: http://tanguay.info/web/index.php?pg=codeExamples&id=358
countries
-france
--paris
--bordeaux
-germany
-italy
subjects
-math
--algebra
--calculus
-science
--chemistry
--biology
other
-this
-that
El código debajo de está tan lejos como lo tengo, pero no trata correctamente con varios hijos de padres.
using System;
using System.Collections.Generic;
using System.Text;
namespace TestRecursive2342
{
class Program
{
static void Main(string[] args)
{
List<OutlineObject> outlineObjects = new List<OutlineObject>();
//convert file contents to object collection
List<string> lines = Helpers.GetFileAsLines();
Stack<OutlineObject> stack = new Stack<OutlineObject>();
foreach (var line in lines)
{
OutlineObject oo = new OutlineObject(line);
if (stack.Count > 0)
{
OutlineObject topObject = stack.Peek();
if (topObject.Indent < oo.Indent)
{
topObject.OutlineObjects.Add(oo);
stack.Push(oo);
}
else
{
stack.Pop();
stack.Push(oo);
}
}
else
{
stack.Push(oo);
}
if(oo.Indent == 0)
outlineObjects.Add(oo);
}
outlineObjects.ForEach(oo => Console.WriteLine(oo.Line));
Console.ReadLine();
}
}
public class OutlineObject
{
public List<OutlineObject> OutlineObjects { get; set; }
public string Line { get; set; }
public int Indent { get; set; }
public OutlineObject(string rawLine)
{
OutlineObjects = new List<OutlineObject>();
Indent = rawLine.CountPrecedingDashes();
Line = rawLine.Trim(new char[] { '-', ' ', '\t' });
}
}
public static class Helpers
{
public static List<string> GetFileAsLines()
{
return new List<string> {
"countries",
"-france",
"--paris",
"--bordeaux",
"-germany",
"-italy",
"subjects",
"-math",
"--algebra",
"--calculus",
"-science",
"--chemistry",
"--biology",
"other",
"-this",
"-that"};
}
public static int CountPrecedingDashes(this string line)
{
int tabs = 0;
StringBuilder sb = new StringBuilder();
foreach (var c in line)
{
if (c == '-')
tabs++;
else
break;
}
return tabs;
}
}
}
gracias, utilicé su patrón if/else para reestructurar mi código y ponerlo a funcionar: http://tanguay.info/web/index.php?pg=codeExamples&id=358 –