![](/img/trans.png)
[英]How to C# WinForm datatable loop through rows and columns to datagridview
[英]How can I have a datatable detect multiple columns when iterating through rows in C# with conditionals?
我是 C# 新手,我必須將 JavaScript 程序重建為 C#。
該程序涉及讀取 CSV 文件並對其進行迭代以檢測不同的值並生成輸出。
這是我的代碼示例:
foreach(DataRow row in results.Rows)
{if (row["Date"].ToString().Substring(row["Date"].ToString().Length - 16) == "2021 12:00:00 AM") //Checks if the year is 2021 or not in the "date" column
{
if (row["State"].ToString() == "CA") //Looks for CA state in the "state" column, however, it appears to not be finding it?
{ //DOES NEEDED CALCULATIONS
基本上,代碼在數據表中檢測到“2021”日期就好了,但是在遍歷行時根本找不到 CA 狀態,因此,永遠不會完成所需的計算。
這是數據表的樣子: DataTable
非常感謝幫助,由於我對 C# 缺乏了解,我被困在這個問題上一段時間。
很可能在row["State"]
中有一些額外的空格
嘗試這個:
foreach(DataRow row in results.Rows)
{if (row["Date"].ToString().Substring(row["Date"].ToString().Length - 16) == "2021 12:00:00 AM") //Checks if the year is 2021 or not in the "date" column
{
if (row["State"].ToString().Contains("CA")) //Looks for CA state in the "state" column, however, it appears to not be finding it?
{ //DOES NEEDED CALCULATIONS
話雖如此,之前的所有評論對您的需求都非常有幫助。 如果不需要,請不要進行自己的 CSV 解析。 不要將DateTime
作為string
。 制作您自己的 DTO 來表示記錄,而不是使用DataTable
。
例子:
record Invoice
{
public int InvoiceNumber { get; set; }
public DateTime Date { get; set; }
public double Amount { get; set; }
public string State { get; set; }
}
public void DoStuff()
{
var invoices = ReadInvoiceFile("Your/Path/Here.csv");
foreach (var invoice in invoices)
{
if(invoice.Date.Year != 2021) continue;
if (invoice.State.Contains("CA"))
{
//do CA specific stuff here
}
}
}
private List<Invoice> ReadInvoiceFile(string path)
{
//realistically you would use a 3rd party library to do this
}
我還要補充一點,您不應該在代碼中使用內聯文字(例如我的示例中的2021
或"CA"
)。 讓你的行為依賴於圍繞硬編碼狀態和年份的 if 語句違反了開閉原則,並且是重構為工廠方法的良好候選者。 但是讓我們一步一步來。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.