C# 有没有办法将CSV文件读入ArrayList,然后在控制台上打印出值?

C# 有没有办法将CSV文件读入ArrayList,然后在控制台上打印出值?,c#,csv,arraylist,C#,Csv,Arraylist,我只是在练习C。我主要习惯于Java,但我一直不知道如何读取.CSV文件,将其存储并将其内容打印到控制台中。这就是我目前所拥有的。我做错了什么 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using Microsoft.VisualBasic.FileIO; using Sys

我只是在练习C。我主要习惯于Java,但我一直不知道如何读取.CSV文件,将其存储并将其内容打印到控制台中。这就是我目前所拥有的。我做错了什么

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Microsoft.VisualBasic.FileIO;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            String path = "C:\\Desktop\\csvTestFilePractice\\";
            String file1 = "testFile1.csv";
            ArrayList arryList1 = new ArrayList();
            String[] dataArray1;

            TextFieldParser CSVFile1 = new TextFieldParser(path + file1);
            CSVFile1.SetDelimiters(",");
            dataArray1 = CSVFile1.ReadFields();

            int count = 0;
            while (!CSVFile1.EndOfData)
            {
                dataArray1 = CSVFile1.ReadFields();
                Console.WriteLine(dataArray1);
            }
            Console.Read();
        }
    }
}
这也是我正在测试的文件

______Excel视图

ID  Name    Phone          State
1   Colt    864-367-8399    SC
2   Terry   864-367-8400    GA
3   Joe     864-367-8401    FL
4   Mark    864-367-8402    NC
5   Ashley  864-367-8403    CO
____记事本视图

ID,Name,Phone,State
1,Colt,864-367-8399,SC
2,Terry,864-367-8400,GA
3,Joe,864-367-8401,FL
4,Mark,864-367-8402,NC
5,Ashley,864-367-8403,CO

感谢您的建议

您无论如何都不应该使用ArrayList,因为它是一种非泛型集合类型。您应该考虑如何将CSV解析为一个列表,以避免必须对对象进行装箱/取消装箱。

无论如何,您不应该使用ArrayList,因为它是一种非泛型集合类型。您应该考虑如何将CSV解析为一个列表,以避免对对象进行装箱/取消装箱操作。

根据此处注释中的问题,提供了一个简短版本的程序,该程序使用每列的最大长度来创建格式字符串。它应该适用于几乎任何csv文件。我相信这是可以改进的。所有列都左对齐

void Main()
{
    List<string[]> lines = new List<string[]>();

    TextFieldParser CSVFile1 = new TextFieldParser(@"g:\test\test.csv");
    CSVFile1.SetDelimiters(",");

    //Loop through the data and create a list.  Each entry in the list
    //is a string array.  This method may be impractical for very large 
    //files.
    while (!CSVFile1.EndOfData)
    {
        lines.Add(CSVFile1.ReadFields());
    }

    //Create a format string using the length of the longest string in each column
    string formatString = createFormatString(lines);

    //Loop through all the lines and write them to the console.
    foreach (var csvLine in lines)
    {
        Console.WriteLine(formatString, csvLine);
    }
}

//Create a format string based on the number of columns and the maximum
// size of each column
private string createFormatString(List<string[]> lines)
{
    var sb = new StringBuilder();

    //Use the first array to get the number of columns.  They should all be the same
    int numberOfColumns = lines[0].Length;

    //Loop through the number of columns and find the max length and append to the format string
    for (int i = 0; i < numberOfColumns; i++)
    {
        int maxColumnWidth = lines.Select(l => l[i].Length).Max();
        sb.AppendFormat("{{{0}, -{1}}}  ", i, maxColumnWidth);
    }

    return sb.ToString();
}
void Main()
{
列表行=新列表();
TextFieldParser CSVFile1=新的TextFieldParser(@“g:\test\test.csv”);
CSVFile1.SetDelimiters(“,”);
//循环遍历数据并创建一个列表。列表中的每个条目
//是字符串数组。此方法对于非常大的
//档案。
而(!CSVFile1.EndOfData)
{
Add(CSVFile1.ReadFields());
}
//使用每列中最长字符串的长度创建格式字符串
string formatString=createFormatString(行);
//循环遍历所有行并将它们写入控制台。
foreach(行中的var csvLine)
{
Console.WriteLine(formatString,csvLine);
}
}
//根据列数和最大值创建格式字符串
//每列的大小
私有字符串createFormatString(列表行)
{
var sb=新的StringBuilder();
//使用第一个数组获取列数。它们都应该相同
int numberOfColumns=行[0]。长度;
//循环遍历列数,找到最大长度并附加到格式字符串
for(int i=0;il[i].Length.Max();
sb.AppendFormat(“{{{0},-{1}}}”,i,maxColumnWidth);
}
使某人返回字符串();
}

根据评论中的问题,这里是该程序的一个简短版本,它使用每列的最大长度来创建格式字符串。它应该适用于几乎任何csv文件。我相信这是可以改进的。所有列都左对齐

void Main()
{
    List<string[]> lines = new List<string[]>();

    TextFieldParser CSVFile1 = new TextFieldParser(@"g:\test\test.csv");
    CSVFile1.SetDelimiters(",");

    //Loop through the data and create a list.  Each entry in the list
    //is a string array.  This method may be impractical for very large 
    //files.
    while (!CSVFile1.EndOfData)
    {
        lines.Add(CSVFile1.ReadFields());
    }

    //Create a format string using the length of the longest string in each column
    string formatString = createFormatString(lines);

    //Loop through all the lines and write them to the console.
    foreach (var csvLine in lines)
    {
        Console.WriteLine(formatString, csvLine);
    }
}

//Create a format string based on the number of columns and the maximum
// size of each column
private string createFormatString(List<string[]> lines)
{
    var sb = new StringBuilder();

    //Use the first array to get the number of columns.  They should all be the same
    int numberOfColumns = lines[0].Length;

    //Loop through the number of columns and find the max length and append to the format string
    for (int i = 0; i < numberOfColumns; i++)
    {
        int maxColumnWidth = lines.Select(l => l[i].Length).Max();
        sb.AppendFormat("{{{0}, -{1}}}  ", i, maxColumnWidth);
    }

    return sb.ToString();
}
void Main()
{
列表行=新列表();
TextFieldParser CSVFile1=新的TextFieldParser(@“g:\test\test.csv”);
CSVFile1.SetDelimiters(“,”);
//循环遍历数据并创建一个列表。列表中的每个条目
//是字符串数组。此方法对于非常大的
//档案。
而(!CSVFile1.EndOfData)
{
Add(CSVFile1.ReadFields());
}
//使用每列中最长字符串的长度创建格式字符串
string formatString=createFormatString(行);
//循环遍历所有行并将它们写入控制台。
foreach(行中的var csvLine)
{
Console.WriteLine(formatString,csvLine);
}
}
//根据列数和最大值创建格式字符串
//每列的大小
私有字符串createFormatString(列表行)
{
var sb=新的StringBuilder();
//使用第一个数组获取列数。它们都应该相同
int numberOfColumns=行[0]。长度;
//循环遍历列数,找到最大长度并附加到格式字符串
for(int i=0;il[i].Length.Max();
sb.AppendFormat(“{{{0},-{1}}}”,i,maxColumnWidth);
}
使某人返回字符串();
}

所以我想用ArrayList做的事情是不可能的吗?不可能。但是新代码中不应该使用
ArrayList
。使用
列表
<代码>列表对应于Java中的
ArrayList
。在这里可以看到更多信息:所以我想用ArrayList做的事情是不可能的吗?不可能。但是,
ArrayList
不应该在新代码中使用。使用
列表
<代码>列表对应于Java中的
ArrayList
。请参阅此处的详细信息:您有以下行:
CSVFile1.SetDelimiters(“,”
),但您的文件似乎没有用逗号分隔。@ChrisDunaway很抱歉,这是一个CSV文件,但我使用excel来提取数据。我将发布记事本数据,而不是您想如何打印它?除了
WriteLine
语句外,您发布的代码似乎没有问题。您可以尝试
Console.WriteLine(string.Join(“,”,dataArray1))
或者如果需要以列格式打印,请尝试
Console.WriteLine({0,2}{1,-10}{2,-14}{3,-5}),dataArray1[0],dataArray1[1],dataArray1[2],dataArray1[3])可能重复的@Andersnk文章没有回答我的具体问题。我发布的代码有一个特定的问题。您有以下行:
CSVFile1.SetDelimiters(“,”
),但您的文件似乎没有用逗号分隔。@ChrisDunaway很抱歉,这是一个CSV文件,但我使用excel提取数据。我将发布记事本数据,而不是您想如何打印它?除了
WriteLine
语句外,您发布的代码似乎没有问题。您可以尝试
Console.WriteLine(string.Join(“,”,dataArray1))
或者如果需要以列格式打印,请尝试
Console.WriteLine({0,2}{1,-10}{2,-14}{3,-5}),dataArray1[0],dataArray1[1],dataArray1[2],dataArray1[3])可能重复的@Andersnk文章没有回答我的具体问题。我发布的代码有一个特定的问题。我的
字符串格式出错