c# - 将数据从 csv 文件加载到键和值字典列表中
问题描述
我有一个包含如下文本列表的文件: 示例 csv 文件 csv 文件包含 3 列。第一列的长度始终为 5。所以我想遍历文件内容,将前 5 个字母存储为键,将剩余的列存储为值。我正在删除它们和 Substringing 之间的逗号,如下所示进行存储。
static string line;
static Dictionary<string, string> stations = new Dictionary<string, string>();
static void Main(string[] args)
{
// Dictionary<string, List<KeyValuePair<string, string>>> stations = new Dictionary<string, List<KeyValuePair<string, string>>>();
var lines = File.ReadAllLines(".\\ariba_sr_header_2017122816250.csv");
foreach (var l in lines)
{
line = l.Replace(",", "");
stations.Add(line.Substring(14),line.Substring(14, line.Length-14));
}
//read all key and value in file
foreach (KeyValuePair<string, string> item in stations)
{
Console.WriteLine(item.Key);
Console.WriteLine(item.Value);
}
Console.ReadLine();
}
调试后,输出为 Output My Expected Result is below: Expected Result
解决方案
干得好:
var stations = new Dictionary<string, string>();
var lines = File.ReadAllLines(@"C:\temp\22.txt");
foreach (var l in lines)
{
var lsplit = l.Split(',');
if (lsplit.Length > 1)
{
var newkey = lsplit[0];
var newval = lsplit[1] + lsplit[2];
stations[newkey] = newval;
}
}
//read all key and value in file
foreach (KeyValuePair<string, string> item in stations)
{
Console.WriteLine(item.Key + " = " + item.Value);
}
Console.ReadLine();
不完全是您期望的输出,但希望它有所帮助。
推荐阅读
- python - train_test_split - 无法对块大小未知的 Dask 数组进行操作
- java - 为什么我们需要在 CharBuffer 中使用 `hasArray()` 方法?
- python - Python:'{0.lower()}'.format('A') 产生 'str' 对象没有属性 'lower()'
- java - 每次 Web 数据更改时,是否有任何方法可以在无需用户干预的情况下解析 Java Web?
- hibernate - Hibernate 是否有特定条件来命名以相同字母开头的列?
- mysql - 如何在MYSQL中有空值的地方进行GROUP_CONCAT?
- asp.net - Asp.net 用图像插入数据,然后用图像在 gridview 上检索它,并且可以在 gridview 上执行编辑更新和删除
- c++ - 为 std::set 重载运算符 < 让我很困惑
- reactjs - 在 safari 和 chrome 中调整窗口高度时保持图像的纵横比
- java - 如何在 SQLite 中插入和检索数据?