簡體   English   中英

如何使用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]);
            }
        }
    }
}

根據您下面的評論:如何將列表數據保存到 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... there is a Chance of SQL Injection 所以通過避免你可以使用存儲過程代替...。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM