C# 在c中如何将一列数据放入列表#

C# 在c中如何将一列数据放入列表#,c#,list,text,C#,List,Text,我希望c#windows窗体应用程序能够将一整列数字放入列表,数据将是一个文本库,例如,它将包含如下4列: 100 200 300 400 100 200 300 400 101 292 83 7312 我可以把整个文本放到一个列表中,但我想有4个不同的列表,如果有意义的话,把每一列放到它自己的列表中 我是否需要阅读每一行以及如何将拆分后的内容添加到列表中 顺便说一句,我并不认为代码可能是实现这一点的最佳方法,如果我走的是正确的道路?你走的是正确的道路。就我个人而言,我喜欢File.Read

我希望c#windows窗体应用程序能够将一整列数字放入列表,数据将是一个文本库,例如,它将包含如下4列:

100 200 300 400
100 200 300 400
101 292 83  7312
我可以把整个文本放到一个列表中,但我想有4个不同的列表,如果有意义的话,把每一列放到它自己的列表中

我是否需要阅读每一行以及如何将拆分后的内容添加到列表中


顺便说一句,我并不认为代码可能是实现这一点的最佳方法,如果我走的是正确的道路?

你走的是正确的道路。就我个人而言,我喜欢
File.ReadAllLines(@“yourTxtFile”)
。在我看来,它使代码变得简单

foreach(var line in File.ReadAllLines(@"yourTxtFile"))
{
   // split and add to the respective lists here
}

我不会将这些值读入单独的列表中。如果您维护单独的列表,您将需要担心保持所有列表同步。我将创建一个对象,您可以使用它保存一行中的所有信息

public class Entry
{
    // give meaningful names to the column values
    public int Column1 { get; set; }
    public int Column2 { get; set; }
    public int Column3 { get; set; }
    public int Column4 { get; set; }

    // overriden to make re-constructing the line for the file easier
    public override string ToString()
    {
        // assuming tab as the delimiter, replace with whatever you're using
        return string.Format("{0}\t{1}\t{2}\t{3}", this.Column1, this.Column2,
            this.Column3, this.Column4);
    }
}
然后,当您读入值时,您可以执行以下操作:

var entries = new List<Entry>();

using (var fStream = File.OpenRead(fileLocation))
using (var reader = new StreamReader(fStream))
{
    while (!reader.EOF)
    {
        var line = reader.ReadLine();

        // assuming tab as the delimiter, replace with whatever you're using
        var parts = line.Split('\t');

        if (parts.Length != 4)
        {
            // whatever you need to do for error handling
            // you could throw an error or just skip to the next line
            continue;
        }

        entries.Add(
            new Entry
            {
                // ideally you'd use int.TryParse to provide further error handling
                Column1 = int.Parse(parts[0]),
                Column2 = int.Parse(parts[1]),
                Column3 = int.Parse(parts[2]),
                Column4 = int.Parse(parts[4])
            }
        );
    }
}

如果这些列是相关的,为什么不将它们存储在数据表中?您尝试了什么?你是在从一个文件,一个UI控件中读取文本吗?我想使用一个列表,这样我就可以使用它们来实现更多的功能,比如从一个文件中读取total columns ect和its,所以我使用stream reader。谢谢我很高兴我走对了:)。我已经有了这方面的代码,我可以将每一行添加到列表中,我正在努力将每一列添加到单独的列表中,因此列表1包含列1数据,依此类推,直到每一列数据的列表为4,如果这有意义的话抱歉,这不是正确的术语哇,这非常有用,我没想到会得到这么多帮助:)我会用这种方式试试,看看我过得怎么样,再次感谢你的帮助
var column1Values = from entry in entries
                    select entry.Column1;