我是C#新手,我必须在C#中重新构建一个JavaScript程序。
此程序涉及读取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#缺乏了解,我在这方面已经坚持了一段时间。
发布于 2021-10-22 09:55:43
很可能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解析。不要以string
的身份在DateTime
上工作。创建自己的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语句违反了开放-封闭原则,并且是重构为工厂方法的一个很好的候选者。但让我们一步一步来。
https://stackoverflow.com/questions/69681099
复制