如何使用c#将列表项及其索引保存在文本文件中

How to save items of list with their index in text file using c#

我已经在 C# 中创建了一个列表,现在我需要将该列表保存在文本文件中,其中包含列表中每个项目的索引吗?请用一个简单的例子来解释。

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

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]);
            }
        }
    }
}

According to your Comment Below: How to save a list data into a SQL Server table. You can follow the same principle from the above code:

代码:

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();
        }
    }
}

Note: by using this syntax new SqlCommand("INSERT INTO tbl_names... there is a Chance of SQL Injection so by avoiding that you can use Store Procedure instead....