阅读文本文件并添加到列表

欣恩

我有一个这样的文本文件。我想逐行阅读并将这些信息存储到List<Store>,其中Store是自定义类型。

Store ID: 01
Name: Kingfisher
Branch Number: 1
Address: 23 Emerson St
Phone: 422361609
-----END OF RECORD-----

Store ID: 02
Name: Harvey
Branch Number: 2
Address: 23 Korby St
Phone: 422361609
-----END OF RECORD-----

Store ID: 175
Name: Roger
Branch Number: 4
Address: 275 Carmody Rd
Phone: 428395719
-----END OF RECORD-----

这是我正在使用的。因为记录总是在列表中显示的顺序,所以我逐行读取和分配store.IDstore.name...,直到达到创纪录的最终属性store.phoneNumber,它然后将其添加到列表并保持持续下一个foreach循环Store ID

但是问题是当我在列表中搜索时,它只能返回最终记录。列表似乎只有一个元素,即最终记录。谁能指出我错了吗?

    var storeTemp = new Store();
    List<Store> stores = new List<Store>();
    foreach (string line in File.ReadAllLines(@"C:\Store.txt"))
    {
        if (line.Contains("Store ID: "))
            storeTemp.ID = line.Substring(10);
        if (line.Contains("Name: "))
            storeTemp.name = line.Substring(6);
        if (line.Contains("Branch Number: "))
            storeTemp.branchNO = Convert.ToInt32(line.Substring(15));
        if (line.Contains("Address: "))
            storeTemp.address = line.Substring(9);
        if (line.Contains("Phone: "))
        {
            storeTemp.phoneNumber = Convert.ToInt32(line.Substring(7));
            stores.Add(storeTemp);
        }
    }
最大限度
        List<Store> stores = new List<Store>();
            var storeTemp = new Store();

        foreach (string line in File.ReadAllLines(@"C:\Store.txt"))
        {
            // You needto create a new instance each time
            if (line.Contains("Store ID: "))
                storeTemp.ID = line.Substring(10);
            if (line.Contains("Name: "))
                storeTemp.name = line.Substring(6);
            if (line.Contains("Branch Number: "))
                storeTemp.branchNO = Convert.ToInt32(line.Substring(15));
            if (line.Contains("Address: "))
                storeTemp.address = line.Substring(9);
            if (line.Contains("Phone: "))
            {
                storeTemp.phoneNumber = Convert.ToInt32(line.Substring(7));
                stores.Add(storeTemp);
                storeTemp = new Store(); // You need to recreate the object, otherwise you overwrite same instance

            }
        }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将对象从文本文件添加到列表

将文本文件内容添加到列表列表中

将文本添加到文本文件的开头

遍历文本文件中的每一行并添加到列表框

从文本文件中读取行并将其添加到列表框

C:将数据从文本文件添加到单链列表中

拆分文本文件条目以添加到数组列表

将文本文件中的双打添加到数组列表中

Applescript,添加到文本文件的底部

将 JSON 数组添加到文本文件

将特定行添加到文本文件

从文本文件添加到列表视图的第一项只是添加了两次

如何将用户输入的号码添加到我的文本文件列表中?

导入、读取和添加到保存在文本文件中的列表的最佳方法是什么?

类似于一个较早的问题“将标题添加到列表文本文件中的列”

将文本文件每一行中的每个字符添加到 Python 列表中

如何从文本文件中提取特定的字符串并将其添加到列表中?

如何将文本文件添加到 bash 脚本中,然后使用该文本文件

将文本添加到文本文件的开头,而不必在R中复制整个文件

Python阅读从文本文件向列表添加多一行

将img标签添加到文本区域以输入文本文件

Bash:使用awk将文本从文本文件添加到变量

从文本文件读取要添加到标签的文本时,在标签中换行

将.pdf添加到文本文件中的文本末尾-bash

通过阅读文本文件返回列表

将列文本文件的标题添加到另一个文件

如何使用cat将文本文件的内容添加到文件的开头

从文件名中提取值并将其添加到文本文件中

使用标题值将列添加到文本文件(文件中的多个标题)