Comment puis-je convertir ce fichier texte contenu dans une collection d'objets récursif que je peux lier à un TreeView? à-dire que je veux finir avec une collection de 3 objets, le premier appelé pays qui a une collection de trois objets enfants: France, Allemagne, italie, et ainsi de suite ...Comment puis-je convertir une liste de plan de fichier texte en une collection récursive d'objets?
RÉPONSE: grâce à tous ceux qui ont aidé à ce sujet, voici mon code qui analyse avec succès ce plan de texte dans un arbre 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
Le code ci-dessous est aussi loin que je l'ai eu, mais il ne traite pas correctement avec plusieurs enfants de parents.
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;
}
}
}
merci, j'ai utilisé votre modèle if/else pour restructurer mon code et je l'ai fait fonctionner: http://tanguay.info/web/index.php?pg=codeExamples&id=358 –