【问题标题】:C# CSV parsing and hiding columns or rows that have true or false valueC# CSV 解析和隐藏具有真值或假值的列或行
【发布时间】:2020-12-11 15:42:35
【问题描述】:

如何使控制台应用程序读取具有 IsHidden 行的 csv 文件(isHidden = false 以显示)

关键是我已经让所有东西都启动并运行了,但是我想不出将 true(hidden) 和 false(true) 行读入控制台应用程序并显示给那些应该的人的逻辑 :D - 对不起我的坏事英语:)

我正在使用的代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PreInterviewTask
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get the data from path.
            string sampleCSV = @"C:\Users\Tomas\source\repos\PreInterviewTask\PreInterviewTask\HistoricalData\HistoricalData.csv";

            string[,] values = LoadCSV(sampleCSV);
            int num_rows = values.GetUpperBound(0) + 1;
            int num_cols = values.GetUpperBound(1) + 1;

            // Display the data to show we have it.

            for (int c = 0; c < num_cols; c++)
                Console.Write(values[0, c] + "\t");

            //Read the data.
            for (int r = 1; r < num_rows; r++)
            {
                //  dgvValues.Rows.Add();
                Console.WriteLine();
                for (int c = 0; c < num_cols; c++)
                {
                    Console.Write(values[r, c] + "\t");
                }
            }

            Console.ReadLine();

        }

        private static string[,] LoadCSV(string filename)
        {
            // Get the file's text.
            string whole_file = System.IO.File.ReadAllText(filename);

            
            // Split into lines.
            whole_file = whole_file.Replace('\n', '\r');
            string[] lines = whole_file.Split(new char[] { '\r' },
                StringSplitOptions.RemoveEmptyEntries);

            // See how many rows and columns there are.
            int num_rows = lines.Length;
            int num_cols = lines[0].Split(',').Length;

           
            // Allocate the data array.
            string[,] values = new string[num_rows, num_cols];
            
            // Load the array.
            for (int r = 0; r < num_rows; r++)
            {
                string[] line_r = lines[r].Split(',');
                for (int c = 0; c < num_cols; c++)
                {
                    values[r, c] = line_r[c];
                }
                
            }

            

            // Return the values.
            return values;
        }
    }

}

我得到的输出:

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

【问题讨论】:

  • 不直接回答你的问题,但请看here。添加bool isHidden = fields[3] == "True"; 应该可以为您解决问题。编码愉快!
  • 你需要澄清你在问什么。很难理解你的意思……“隐藏具有真值或假值的列或行”……这没有意义。行和列是两个不同的东西。如果一行或一列有“假”,那么您怎么知道隐藏该行或仅隐藏该列?此外,很高兴您显示您的代码输出和预期输出,但是,如果没有看到您正在读取的 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 所以客户端 4 和 5 应该是隐藏的,这就是我意思是:) 抱歉

标签: c# csv parsing console-application


【解决方案1】:

看看以下是否有帮助。我使用您的输出作为输入,因为我没有实际输入。 :

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication176
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.csv";
        static void Main(string[] args)
        {
            Menu menu = new Menu(FILENAME);

            List<Menu> sortedRows = Menu.items.OrderBy(x => x).ToList();
            menu.Print(sortedRows);
            Console.ReadLine();
        }
    }
    public class Menu : IComparable
    {
        public static List<Menu> items { get; set; }
        public int ID { get; set; }
        public string name { get; set; }
        public int? parent { get; set; }
        public Boolean hidden { get; set; }
        public string[] linkUrl { get; set; }

        public Menu() { }
        public Menu(string filename)
        {
            StreamReader reader = new StreamReader(filename);
            string line = "";
            int rowCount = 0;
            while ((line = reader.ReadLine()) != null)
            {
                line = line.Trim();
                if (line.Length > 0)
                {
                    if (++rowCount  == 1)
                    {
                        items = new List<Menu>();
                    }
                    else
                    {
                        Menu newMenu = new Menu();
                        items.Add(newMenu);
                        string[] splitArray = line.Split(new char[] { ';' }).ToArray();
                        newMenu.ID = int.Parse(splitArray[0]);
                        newMenu.name = splitArray[1];
                        newMenu.parent = (splitArray[2] == "NULL")? null : (int?)int.Parse(splitArray[2]);
                        newMenu.hidden = Boolean.Parse(splitArray[3]);
                        newMenu.linkUrl = splitArray[4].Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
                    }

                }
            }
        }
        public int CompareTo(object obj)
        {
            Menu other = (Menu)obj;
            int min = Math.Min(this.linkUrl.Length, other.linkUrl.Length);

            for (int i = 0; i < min; i++)
            {
                int compare = this.linkUrl[i].CompareTo(other.linkUrl[i]);
                if (compare != 0) return compare;
            }
            return this.linkUrl.Length.CompareTo(other.linkUrl.Length);
        }
        public void Print(List<Menu> rows)
        {
            foreach (Menu menu in rows)
            {
                if (!menu.hidden)
                {
                    int length = menu.linkUrl.Length - 1;
                    Console.WriteLine(".{0} {1}", new string('.', 3 * length), menu.name);
                }
            }
        }
    }

}

【讨论】:

  • 需要删除“.ToArray()”。应该是string[] splitArray = line.Split(new char[] { ';' });string[] pathLength = splitArray[4].Split(new char[] { '/' });
  • 我看到你做了什么,我喜欢它,但主要问题是客户端 4 和 5 是隐藏的,忘了说 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
  • 菜单项应根据它们所属的父项缩进。 -有些项目是隐藏的,不应该出现 -这些项目应该按字母顺序排列
  • 非常感谢
猜你喜欢
  • 1970-01-01
  • 2017-11-20
  • 2019-08-20
  • 2016-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-17
  • 2014-05-10
相关资源
最近更新 更多