c# - 如何使用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...
有一个 SQL 注入的机会,所以通过避免你可以使用存储过程来代替......
推荐阅读
- java - 如何禁用 Recyclerview 中其他项目的 onTouch?
- forms - 以redux形式复制表单数组中的字段和值
- lua - 如何同时将 bool 变量设置为 true 和 false?
- ruby-on-rails - 带有 grant_type=password 的 CURL API 令牌请求
- python - 从具有相似值的numpy数组中查找给定大小的补丁
- python - Numpy数组迭代
- android - 带有 C++Builder 的 Android 的 TradioButton 模态输入框
- excel - 如何使用宏“冻结”excel中的单元格
- python - python 2.7 与第 11 代 Intel Core i9 的兼容性问题?
- python - Numba 函数需要很长时间才能为数组赋值