读取csv文件并返回缩进的菜单c#。

问题描述 投票:0回答:1

我必须从一个.csv文件中使用以下数据创建一个缩进的导航菜单。

ID;MenuName;ParentID;isHidden;LinkURL 1;公司;NULL;False;公司2;关于我们;1;False;companyaboutus 3;任务;1;False;companyymission 4;团队;2;False;companyaboutusteam 5;客户端2。 10;False;referencesclient2 6;客户端1;10;False;referencesclient1 7;客户端4;10;True;referencesclient4 8;客户端5;10;True;referencesclient5 10;References;NULL;False;References

使用这些数据,我必须开发一个应用程序,该应用程序将解析文件,并在控制台中显示内容,如下面的例子。

. 公司...... 关于我们....... 团队....... 使命......。参考资料 ........ 客户1 ...... 客户2

菜单项应该缩进(取决于父项),隐藏项(isHidden==true)不应该呈现,项目应该按字母顺序排列。到目前为止,我已经尝试过了。

using (StreamReader sr = new StreamReader(@"file.csv"))
        {
            // Read the stream to a string, and write the string to the console.
            string [] lines = sr.ReadToEnd().Split(/*';', */'\n');                
            for (int i = 1; i < lines.Length; i++)
            {                    
                Console.WriteLine($"String no {i} is : {lines[i-1]}");
            }                
        }

用这个方法我得到了线条,但之后我就卡住了。我是一个新的编码,所以任何帮助将是感激:)

c# csv indentation
1个回答
0
投票

下面是一些代码,应该能帮助你脱身。

工作样本。

https:/dotnetfiddle.netL37Gjr。

它首先将数据解析成一个独立的对象。然后这个对象被用来建立一个m-ary树,或者说是一个连接节点的层次结构。一个节点有0个或多个子节点的引用)。

https:/en.wikipedia.orgwikiM-ary_tree)。

然后使用树形遍历(如果你需要了解更多,请使用google)来插入和打印输出,然而还是有一些问题。它现在使用级别顺序遍历来打印,然而这出现了一个错误。

Found root:1 - Company
Found root:10 - References
-------------------
1 - Company
    2 - About Us
    3 - Mission
        4 - Team
10 - References
    6 - Client 1
    5 - Client 2

如你所见,它的打印结果是 4 - Team 在错误的层次上。我将把它留给你来修复它(因为我没有时间了),如果没有,我希望我给你很多想法,让你自己去研究。

// sample for https://stackoverflow.com/questions/61395486/read-csv-file-and-return-indented-menu-c-sharp by sommmen

using System;
using System.Collections;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public class Node<T>
    {
        public T Data {get;set;}    
        public List<Node<T>> Children { get; set;}

        public Node()
        {
            Children = new List<Node<T>>();
        }

        // Tree traversal in level order
         public List<Node<T>> LevelOrder()
        {
            List<Node<T>> list = new List<Node<T>>();
            Queue<Node<T>> queue = new Queue<Node<T>>();
            queue.Enqueue(this);
            while(queue.Count != 0)
            {               
                Node<T> temp = queue.Dequeue();
                foreach (Node<T> child in temp.Children)
                    queue.Enqueue(child);
                list.Add(temp);
            }
            return list;
        }

        public List<Node<T>> PreOrder()
        {
            List<Node<T>> list = new List<Node<T>>();
            list.Add(this);
            foreach (Node<T> child in Children)
                list.AddRange(child.PreOrder());
            return list;
        }

        public List<Node<T>> PostOrder()
        {
            List<Node<T>> list = new List<Node<T>>();
            foreach (Node<T> child in Children)
                list.AddRange(child.PreOrder());
            list.Add(this);
            return list;
        }


    }

    public class Entity
    {
        public int id   {get;set;}
        public string menuName {get;set;}
        public int? parentID {get;set;}
        public bool isHidden {get;set;}
        public string linkURL  {get;set;}
    }

    public static void Main()
    {
        var data = @"ID;MenuName;ParentID;isHidden;LinkURL
1;Company;NULL;False;/company
2;About Us;1;False;/company/aboutus
3;Mission;1;False;/company/mission
4;Team;2;False;/company/aboutus/team
5;Client 2;10;False;/references/client2
6;Client 1;10;False;/references/client1
7;Client 4;10;True;/references/client4
8;Client 5;10;True;/references/client5
10;References;NULL;False;/references";

        var lines = data.Split('\n');

        var rootNodes = new List<Node<Entity>>();
        var childItems = new List<Entity>();

        // Parse the data to entities
        // Items without a parent are used as rootnodes to build a tree
        foreach(var row in lines.Skip(1))
        {           
            var columns = row.Split(';');

            var id       = Convert.ToInt32(columns[0]);
            var menuName = columns[1];
            var parentID = ToNullableInt(columns[2]);
            var isHidden = Convert.ToBoolean(columns[3]);
            var linkURL  = columns[4];

            var entity = new Entity()
                              {
                                id = id,
                                  menuName = menuName,
                                  parentID = parentID,
                                  isHidden = isHidden,
                                  linkURL = linkURL
                              };

            if(parentID == null)
            {
                Console.WriteLine("Found root:" + entity.id + " - " + entity.menuName);

                rootNodes.Add(new Node<Entity>()
                              {
                                  Data = entity
                              });
            }
            else
            {
                childItems.Add(entity); 
            }
        }

        // Add the childElements to their appropriate rootnode

        foreach(var rootNode in rootNodes)
        {
            foreach(var childItem in childItems.OrderBy(a=>a.parentID).ThenBy(b=>b.menuName))
            {
                var newNode = new Node<Entity>()
                {
                    Data = childItem
                };

                Insert(rootNode, newNode);
            }
        }

        Console.WriteLine("-------------------");

        foreach(var rootNode in rootNodes)
        {
            var indent = 0;
            var previous = rootNode;
            foreach(var node in rootNode.LevelOrder())
            {
                if(node.Data.isHidden) continue;

                if(previous.Data.parentID != node.Data.parentID)
                    indent++;

                for(var i = 0; i < indent; i++)
                    Console.Write("\t");

                Console.WriteLine(node.Data.id + " - " + node.Data.menuName);
                previous = node;
            }
        }
    }

    public static void Insert(Node<Entity> rootNode, Node<Entity> targetNode)
    {
        foreach(var current in rootNode.LevelOrder())
        {
            if(current.Data.id == targetNode.Data.parentID)
            {
                current.Children.Add(targetNode);   
                return;
            }
        }
    }

    public static int? ToNullableInt(string s)
    {
        int i;
        if (int.TryParse(s, out i)) return i;
        return null;
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.