c# - C# - 从 CSV 文件中读取数据并在 DataGridView 中显示
问题描述
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnLoad_Click(object sender, EventArgs e)
{
dgvData.DataSource = LoadCSV(@"C:\working\Summary.csv");
}
public List<Product> LoadCSV(string csvFile)
{
var query = from line in File.ReadAllLines(csvFile)
let data = line.Split(',')
select new Product
{
A = data[0],
B = data[1]
};
return query.ToList();
}
public class Product
{
public string A { get; set; }
public string B { get; set; }
}
}
我是一名初学者,从上周开始使用 C# 工作。
.csv
读取包含简单数字的文件,但其中包含导致错误的空格
System.IndexOutOfRangeException
解决方案
以下是该方法的简化非LINQ
版本,LoadCSV()
它可以帮助您在代码中更好地理解您的场景。方法 -
Product
仅当该行具有任何值时才创建- 创建
Product
with only 属性A
B
仅当第二个值可用时才为属性设置值
public List<Product> LoadCSV(string csvFile)
{
// create an empty list
var list = new List<Product>();
// read all the lines
var lines = File.ReadAllLines(csvFile);
// do some processing for each line
foreach (var line in lines)
{
// split line based on comma, only if line is not an empty string
// if line is an empty string, skip processing
var data = line.Split(',', StringSplitOptions.RemoveEmptyEntries);
if (data.Length == 0)
continue;
// we skipped empty lines, so data has at least one element
// we can safely create a Product with the first element for property A
var product = new Product { A = data[0] };
// if data has more than one element, then we have a second element
// we can safely assign the second element to property B
if (data.Length > 1)
{
product.B = data[1];
}
// add the product to list
list.Add(product);
}
return list;
}
推荐阅读
- python - 更高效的双 For 循环超过 70k 个变量?
- javascript - 复制一个工作表中的选定列并将它们添加到另一个工作表中的选定列
- javascript - 在 JavaScript 中初始化 html 元素以实现可重用性的最佳方法?
- php - PHP Curl 请求导致 504 网关超时
- sql - 在 Hibernate 原生查询中排序
- firebase - 仍然会引发“firebase_auth/email-already-in-use”异常,尽管在 firebase_auth flutter 中注册了一个独特的电子邮件
- php - 如何将文本插入另一个文件 [file_put_contents]
- python - 根据多个条件乘以熊猫列
- variables - SAS:中间有缺失值的枚举组变量
- winapi - WinApi:WTSQueryUserToken() 文档说不泄漏令牌,如何泄漏令牌?