首页 > 解决方案 > 如何使用c#将列表项及其索引保存在文本文件中

问题描述

我已经在 c# 中创建了一个列表,现在我需要将列表保存在文本文件中,并为列表中的每个项目提供索引?请用一个简单的例子来解释。

标签: c#c#-2.0

解决方案


试试这个代码:我希望你能从中得到基本的想法。

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> _names = new List<string>()
            {
                "Rehan",
                "Hamza",
                "Adil",
                "Arif",
                "Hamid",
                "Hadeed"
            };

            using (StreamWriter outputFile = new StreamWriter(@"E:\test.txt")
            {
                foreach (string line in _names)
                    outputFile.WriteLine(line);
            }
        }
    }
}

或者你也应该尝试 for 循环。

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> _names = new List<string>()
            {
                "Rehan",
                "Hamza",
                "Adil",
                "Arif",
                "Hamid",
                "Hadeed"
            };

            using (StreamWriter outputFile = new StreamWriter(@"E:\test.txt")
            {
                for (int index = 0; index < _names.Count; index++)
                    outputFile.WriteLine("Index : " + index + " - " + _names[index]);
            }
        }
    }
}

根据您在下面的评论: 如何将列表数据保存到 SQL Server 表中。您可以从上面的代码中遵循相同的原则:

代码:

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Table 
            // -------------
            // | ID | Name |
            // -------------

           // Please Not that: ID Column in a database should not be identity Colomn because in this example i am going to add data to ID Column explicity...                

            // List of name that we are going to save in Database.
            List<string> _names = new List<string>()
            {
                "Rehan",
                "Hamza",
                "Adil",
                "Arif",
                "Hamid",
                "Hadeed"
            };

            SqlConnection connection = new SqlConnection("Connection string goes here...");
            connection.Open();
            for (int index = 0; index < _names.Count; index++)
            {
                SqlCommand command = new SqlCommand("INSERT INTO tbl_names (id,name) VALUES ('"+index+"', '"+_names[index]+"')",connection);
                command.ExecuteNonQuery();
            }
            connection.Close();
        }
    }
}

注意:通过使用这种语法new SqlCommand("INSERT INTO tbl_names...有一个 SQL 注入的机会,所以通过避免你可以使用存储过程来代替......


推荐阅读