C#读取Excel的Timeout字段返回System.Collections.Generic.List`1[System.Char]问题
问题复现代码:
var Timeout = rows[i]["Timeout"].ToString().ToList();
问题原因
C# 中 string 类型默认实现了 IEnumerable<char> 接口,属于可枚举的字符集合。你在拿到字段的字符串结果后直接调用 LINQ 提供的 ToList() 方法,会直接把字符串拆分为单个字符的集合,最终返回的就是 List<char> 类型,和你预期的字段值完全不符。
解决方案
根据你的实际需求选择对应处理方式:
- 如果你仅需要获取当前行的Timeout字段单值,不需要调用
ToList(),直接转为对应类型即可:// 字段为数值类型时的写法 int timeout = Convert.ToInt32(rows[i]["Timeout"]); // 字段为字符串类型时的写法,兼容空值情况 string timeout = rows[i]["Timeout"]?.ToString() ?? string.Empty; - 如果你需要收集所有行的Timeout字段值到列表中,需要将遍历逻辑和
ToList()的调用位置调整到外层:// 收集所有行的数值型Timeout到列表 List<int> timeoutList = rows.Select(r => Convert.ToInt32(r["Timeout"])).ToList(); // 收集所有行的字符串型Timeout到列表 List<string> timeoutStrList = rows.Select(r => r["Timeout"]?.ToString() ?? string.Empty).ToList();
内容的提问来源于stack exchange,提问作者Madhu
相关产品推荐
相关产品推荐

