[英]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.