C# 使用CSV文件

C# 使用CSV文件,c#,linq,sorting,csv,C#,Linq,Sorting,Csv,我已经花了整整一周的时间来解决这个问题,现在我想知道我是否可以解决这个问题,而不必深入研究C语言,我对C语言还相当陌生,还需要处理CSV文件并对它们进行排序和组织,所以我对这方面的所有方面都缺乏经验 我正在尝试按字母顺序对CSV文件进行排序,隐藏需要隐藏的项目,并根据它们的父元素、子元素和孙子元素设置深度级别 我已经成功地编写了一些代码,但我不知道如何按字母顺序对它们进行排序,并根据它们所属的父级和子级为它们提供适当的深度层 以下是我一直试图组织的模型CSV: ID;MenuName;Paren

我已经花了整整一周的时间来解决这个问题,现在我想知道我是否可以解决这个问题,而不必深入研究C语言,我对C语言还相当陌生,还需要处理CSV文件并对它们进行排序和组织,所以我对这方面的所有方面都缺乏经验

我正在尝试按字母顺序对CSV文件进行排序,隐藏需要隐藏的项目,并根据它们的父元素、子元素和孙子元素设置深度级别

我已经成功地编写了一些代码,但我不知道如何按字母顺序对它们进行排序,并根据它们所属的父级和子级为它们提供适当的深度层

以下是我一直试图组织的模型CSV:

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
我已经用分号分隔了项目,我已经显示了需要显示的项目,但是我没有按照我应该的方式对它们进行排序

排序应如下所示:

Company
  About Us
    Team
  Mission
References
  Client 1
  Client 2
Company
  About Us
  Mission
    Team
  Client 2
  Client 1
References
Company
  About Us
  Mission
    Team
        Client 2
        Client 1
References
我试图通过获取斜杠的索引来对它们进行排序或按顺序显示,但代码复制的不是它应该如何显示,它看起来是这样的:

Company
  About Us
    Team
  Mission
References
  Client 1
  Client 2
Company
  About Us
  Mission
    Team
  Client 2
  Client 1
References
Company
  About Us
  Mission
    Team
        Client 2
        Client 1
References
在另一次尝试中,我递归地将它们的父id与id匹配,控制台显示如下所示:

Company
  About Us
    Team
  Mission
References
  Client 1
  Client 2
Company
  About Us
  Mission
    Team
  Client 2
  Client 1
References
Company
  About Us
  Mission
    Team
        Client 2
        Client 1
References
我和一个朋友试过解决这个问题,即使他也不知道如何解决这个问题,因为这段代码应该在使用不同父ID的不同文件上工作

最重要的是,我无法将它们索引到数组中,因为只有索引0,或者索引基于它们的字母,或者如果我输入索引位置1,控制台将崩溃

以下是我未能对它们进行排序的第一部分的代码:

class Program
{
    static void Main(string[] args)
    {
        StreamReader sr = new StreamReader(@"Navigation.csv");
        string data = sr.ReadLine();

        while (data != null)
        {
            string[] rows = data.Split(';');
            int id;
            int parentId;
            bool ids = Int32.TryParse(rows[0], out id);
            string name = rows[1];
            bool pIds = Int32.TryParse(rows[2], out parentId);
            string isHidden = rows[3];
            string linkUrl = rows[4];
            string[] splitted = linkUrl.Split('/');

            if (isHidden == "False")
            {
                List<CsvParentChild> pIdCid = new List<CsvParentChild>()
                {
                    new CsvParentChild(id, parentId, name, linkUrl)
                };
            }

            data = sr.ReadLine();
        }
    }
}

class CsvParentChild
{

    public int Id;
    public int ParentId;
    public string Name;
    public string LinkUrl;
    public List<CsvParentChild> Children = new List<CsvParentChild>();

    public CsvParentChild(int id, int parentId, string name, string linkUrl)
    {

        Id = id;
        ParentId = parentId;
        Name = name;
        LinkUrl = linkUrl;
        string[] splitted = linkUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

        if (splitted.Length == 1)
        {
            Console.WriteLine($". { name }");
        }
        else if (splitted.Length == 2)
        {
            Console.WriteLine($".... { name }");
        }
        else if (splitted.Length == 3)
        {
            Console.WriteLine($"....... { name }");
        }
    }
}
类程序
{
静态void Main(字符串[]参数)
{
StreamReader sr=新的StreamReader(@“Navigation.csv”);
字符串数据=sr.ReadLine();
while(数据!=null)
{
string[]rows=data.Split(“;”);
int-id;
int-parentId;
bool id=Int32.TryParse(行[0],out id);
字符串名称=行[1];
bool-pIds=Int32.TryParse(第[2]行,out-parentId);
字符串isHidden=行[3];
字符串linkUrl=行[4];
string[]splitted=linkUrl.Split('/');
如果(isHidden==“False”)
{
List pIdCid=新列表()
{
新的CsvParentChild(id、parentId、名称、链接URL)
};
}
data=sr.ReadLine();
}
}
}
CsvParentChild类
{
公共int Id;
公共int-ParentId;
公共字符串名称;
公共字符串链接URL;
public List Children=new List();
公共CsvParentChild(int-id、int-parentId、字符串名称、字符串链接URL)
{
Id=Id;
ParentId=ParentId;
名称=名称;
LinkUrl=LinkUrl;
string[]splitted=linkUrl.Split(新字符[]{'/'},StringSplitOptions.RemoveEmptyEntries);
如果(拆分的长度==1)
{
WriteLine($“{name}”);
}
else if(splitted.Length==2)
{
WriteLine($“…{name}”);
}
else if(splitted.Length==3)
{
Console.WriteLine($“…{name}”);
}
}
}
下面是第二部分:

class Program
{
    static void Main(string[] args)
    {
        // Get the path for the file
        const string filePath = @"../../Navigation.csv";

        // Read the file
        StreamReader sr = new StreamReader(File.OpenRead(filePath));
        string data = sr.ReadLine();

        while (data != null)
        {

            string[] rows = data.Split(';');

            ListItems lis = new ListItems();

            int id;
            int parentId;

            // Get the rows/columns from the Csv file
            bool ids = Int32.TryParse(rows[0], out id);
            string name = rows[1];
            bool parentIds = Int32.TryParse(rows[2], out parentId);
            string isHidden = rows[3];
            string linkUrl = rows[4];

            // Split the linkUrl so that we get the position of the
            // elements based on their slash
            string [] splitted = linkUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            // If item.isHidden == "False"
            // then display the all items whose state is set to false.
            // If the item.isHidden == "True", then display the item
            // whose state is set to true.
            if (isHidden == "False")
            {
                // Set the items
                ListItems.data = new List<ListItems>()
                {
                    new ListItems() { Id = id, Name = name, ParentId = parentId },
                };

                // Make a new instance of ListItems()
                ListItems listItems = new ListItems();

                // Loop through the CSV data
                for (var i = 0; i < data.Count(); i++)
                {
                    if (splitted.Length == 1)
                    {
                        listItems.ListThroughItems(i, i);
                    }
                    else if (splitted.Length == 2)
                    {
                        listItems.ListThroughItems(i, i);
                    }
                    else
                    {
                        listItems.ListThroughItems(i, i);
                    }
                }
            }

            // Break out of infinite loop
            data = sr.ReadLine();
        }
    }

public class ListItems
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int ParentId { get; set; }
        public static List<ListItems> data = null;
        public List<ListItems> Children = new List<ListItems>();

        // http://stackoverflow.com/a/36250045/7826856
        public void ListThroughItems(int id, int level)
        {
            Id = id;

            // Match the parent id with the id
            List<ListItems> children = data
                .Where(p => p.ParentId == id)
                .ToList();

            foreach (ListItems child in children)
            {
                string depth = new string('.', level * 4);
                Console.WriteLine($".{ depth } { child.Name }");
                ListThroughItems(child.Id, level + 1);
            }
        }
    }
}
类程序
{
静态void Main(字符串[]参数)
{
//获取文件的路径
常量字符串文件路径=@“../../Navigation.csv”;
//读文件
StreamReader sr=新的StreamReader(File.OpenRead(filePath));
字符串数据=sr.ReadLine();
while(数据!=null)
{
string[]rows=data.Split(“;”);
ListItems lis=新ListItems();
int-id;
int-parentId;
//从Csv文件中获取行/列
bool id=Int32.TryParse(行[0],out id);
字符串名称=行[1];
bool parentId=Int32.TryParse(第[2]行,out parentId);
字符串isHidden=行[3];
字符串linkUrl=行[4];
//拆分链接URL,以便获得
//基于斜杠的元素
string[]splitted=linkUrl.Split(新字符[]{'/'},StringSplitOptions.RemoveEmptyEntries);
//如果item.ishiden==“False”
//然后显示状态设置为false的所有项目。
//如果item.ishiden==“True”,则显示该项
//其状态设置为true。
如果(isHidden==“False”)
{
//设置项目
ListItems.data=新列表()
{
新建ListItems(){Id=Id,Name=Name,ParentId=ParentId},
};
//创建ListItems()的新实例
ListItems ListItems=新ListItems();
//循环浏览CSV数据
对于(var i=0;i http://www.apache.org/licenses/LICENSE-2.0
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication49
    {
    class Program
    {
        static void Main(string[] args)
        {
            List<csvRow> unsortedRows = new List<csvRow>();
            const string filePath = @"Navigation.csv";
            StreamReader sr = new StreamReader(File.OpenRead(filePath));
            string data = sr.ReadLine();
            while (data != null)
            {
                var dataSplit = data.Split(';');   
                //We need to avoid parsing the first line. 
                if (dataSplit[0] != "ID" )
                {
                    csvRow lis = new csvRow(dataSplit);
                    unsortedRows.Add(lis);
                }
                // Break out of infinite loop
                data = sr.ReadLine();
            }
            sr.Dispose();
            var roots = unsortedRows.Where(row => row.ParentId.HasValue == false).
                OrderBy(root => root.MenuName).ToList();

            foreach (csvRow root in roots)
            {
                root.addChildrenFrom(unsortedRows);
            }

            foreach (csvRow root in roots)
            {
                foreach (string FamilyMember in root.FamilyTree)
                {
                    Console.WriteLine(FamilyMember);
                }
            }
            Console.Read();
        }
    }
    public partial class csvRow
    {
        // Your Data
        public int Id { get; private set; }
        public string MenuName { get; private set; }
        public int? ParentId { get; private set; }
        public bool isHidden { get; private set; }
        public string LinkURL { get; private set; }

        public csvRow(string[] arr)
        {
            Id = Int32.Parse(arr[0]);
            MenuName = arr[1];
            ParentId = ToNullableInt(arr[2]);
            isHidden = bool.Parse(arr[3]);
            LinkURL = arr[4];
        }
        private static int? ToNullableInt(string s)
        {
            int i;
            if (int.TryParse(s, out i))
                return i;
            else
                return null;
        }
        private List<csvRow> children = new List<csvRow>();
        public List<csvRow> ChildrenSorted
        {
            get
            {
                return children.OrderBy(row => row.MenuName).ToList();
            }
        }
        public void addChildrenFrom(List<csvRow> unsortedRows)
        {
            this.children.AddRange(unsortedRows.Where(
                row => row.ParentId.HasValue &&
                row.ParentId == this.Id &&
                !this.children.Any(child => child.Id == row.Id)));
            foreach (csvRow child in this.children)
            {
                child.addChildrenFrom(unsortedRows);
            }
        }
        public List<string> FamilyTree
        {
            get
            {
                List<string> myFamily = new List<string>();
                myFamily.Add(this.MenuName);
                foreach (csvRow child in this.ChildrenSorted)
                {
                    foreach (string familyMember in child.FamilyTree)
                    {
                        myFamily.Add("\t" + familyMember);
                    }
                }
                return myFamily;
            }
        }
    }
}