C# 从文本文件中读取,并将每一行拆分为不同的数组或列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9763796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:45:55  来源:igfitidea点击:

Reading from a text file, and splitting each individual line into different arrays or lists

c#design-patternsc#-4.0

提问by

I'm trying to figure out the best way to solve a problem in my program. Basically, I've got a listbox that holds book codes(1,2,3, etc). 1, 2, 3 would represent 3 different books. I have a text file that holds information such as:

我正在尝试找出解决程序中问题的最佳方法。基本上,我有一个包含书籍代码(1、2、3 等)的列表框。1, 2, 3 将代表 3 本书。我有一个文本文件,其中包含以下信息:

Text file format:
bookCode, bookTitle, bookPrice, quantityofBooks

文本文件格式:
bookCode、bookTitle、bookPrice、quantityofBooks

Text file dummy information:
1, Book One, 22, 5
2, Book Two, 10, 3
3, Book Three, 5, 15

文本文件虚拟信息:
1、第一册、22、5
2、第二册、10、3
3、第三册、5、15

I don't always know how many lines there will be in this text file. What I'm trying to do is to split each individual line and put each line into some sort of array or list, and have the ability to access each individual item in those individual lists (items such as: Book One, Book Two, so that I can put these into a listbox) And, say for example someone clicks on "Book Two" in the list box, my label will change with the price for Book Two.

我并不总是知道这个文本文件中有多少行。我想要做的是分割每一行并将每一行放入某种数组或列表中,并能够访问这些单独列表中的每个单独项目(项目例如:第一本书、第二本书,所以我可以将这些放入列表框中)并且,例如有人单击列表框中的“第二本书”,我的标签将随着第二本书的价格而变化。

How can I put the bookTitle (Book One, Book Two, etc) into a listbox, and how can I split each line into separate lists and each individual items for that line into a list?

如何将书名(第一本书、第二本书等)放入列表框中,以及如何将每一行拆分为单独的列表并将该行的每个单独项目拆分为一个列表?

I'm not quite sure I've explained what I want as well as it could be explained. So I apologise if this has come across mind boggling.

我不太确定我已经解释了我想要的以及可以解释的内容。因此,如果这令人难以置信,我深表歉意。

采纳答案by Micah Armantrout

declare this class

声明这个类

 public class Book
 {
      string BookName;
      int bookCode;   
      decimal bookPrice;
      int bookQuanity;
 }

Then read from the file using this code:

然后使用以下代码从文件中读取:

 List<Book> Books = new List<Book>();
 using (StreamReader sr = new StreamReader(path)) 
 {
    while (sr.Peek() >= 0) 
    {
      string str;
      string[] strArray;
      str = sr.ReadLine();

      strArray = str.split(',');
      Book currentBook = new Book();
      currentBook.bookCode = strArray[0];
      currentBook.BookName = strArray[1];
      currentBook.bookPrice = double.Parse(strArray[2]);
      currentBook .bookCode = int.Parse(strArray[3]);

      Books.Add(currentBook);





    }
 }


//listbox = the name you gave your listbox
          listbox.DataSource = Books;
          listbox.ValueMember = "bookCode";
          listbox.DisplayMember = "BookName";

回答by Shyju

I would create class for the Book first

我会先为这本书创建课程

public class Book
{
  public int BookCode { set;get;}
  public string BookTitle { set;get; }
  public decimal BookPrice { set;get}
  public int Quantity { set;get;"

}

}

Read from your datasource( in this case the text file) and store it in a List of our Book Class

从您的数据源(在本例中为文本文件)读取并将其存储在我们的图书类列表中

List<Book> bookList=new List<Book>();
bookList=BookManager.GetBookList();  // gets the list of books read from the text file.

Store this in your global scope so that you can access it from any of your methods in the form.

将此存储在您的全局范围内,以便您可以从表单中的任何方法访问它。

When you want to access specific data about a book use Linq to get it

当您想访问有关一本书的特定数据时,请使用 Linq 来获取它

var book=(from p in bookList where p.BookCode=2).FirstOrDefault();
if(book !=null)
{
  lblPrice.Text=book.BookPrice.ToString();
}

To put the BookTitles to a List box, you can mention the DataTextField as BookTitle when you bind that.

要将 BookTitles 放入列表框,您可以在绑定 DataTextField 时将其提及为 BookTitle。

 lstBooks.DataSource=bookList;
 lstBooks.DataValueField="BookCode";
 lstBooks.DataTextField="BookTitle ";
 lstBooks.DataBind();

To Read the file from your text file and fill it to your list of Book object, do some thing like this

要从文本文件中读取文件并将其填充到 Book 对象列表中,请执行以下操作

public List<Book> GetBookList()
{
  List<Book> objBooks=new List<Book>();

  using (StreamReader file = new StreamReader(@"C:\dataist.txt"))
        {
            while ((line = file.ReadLine()) != null)
            {

                char[] delimiters = new char[] { ',' };
                string[] parts = line.Split(delimiters);

                 Book objBook=new Book();
                 objBook.BookCode=parts[0];
                 objBook.BookTitle =parts[0];
                 objBook.BookPrice =Convert.ToDecimal(parts[0]);
                 objBook.Quantity =Convert.ToInt32(parts[0]);

                 objBooks.Add(objBook);

            }

            file.Close();
        }

return objBooks;
}

If possible, I will store the book details to a database table. It is more easy to manage and maintain and i dont need to worry about reading and writing to file.

如果可能,我会将书籍详细信息存储到数据库表中。它更易于管理和维护,我无需担心读取和写入文件。

I am assuming you are doing this for a windows form app.

我假设您正在为 Windows 窗体应用程序执行此操作。

回答by David Parker

             Book objBook = new Book();
             objBook.BookCode=Convert.ToInt32(parts[0]);
             objBook.BookTitle =parts[0];
             objBook.BookPrice =Convert.ToDecimal(parts[0]);
             objBook.Quantity =Convert.ToInt32(parts[0]);