我如何使用 foreach 在 C# 中使用条件语句在数据表中提前查找一个变量?

How can I use foreach to look one variable ahead in the datatable with conditionals in C#?

你们帮我解决了我的最后一个问题,现在我有了另一个问题。

我是 C# 的新手,我必须遍历数据table 来计算不同状态的事务。但是,我必须删除重复的交易。我在 javascript 中有类似的东西,我在 table 中取了一个变量,如果它与当前变量匹配,那么它将从计数器中减去一个。

我如何在 C# 中执行此操作?这是我一直在尝试但没有成功的方法:

if (row["State"].ToString().Contains("CA")) //Looks for CA state in the "state" column, however, it appears to not be finding it?
            {
                californiaTransactions2021 += 1;
               if(row["InvNum"].ToString() == row["InvNum"]+1.ToString())
                {
                    californiaTransactions2021 -= 1;
                }

这是我的数据table 的样子:

如您所见,一些发票号码在加州是相同的,必须从柜台减去。 C# 在循环中执行此操作的正确语法是什么?

如果我需要向前看,我需要使用foreach(而不是通过索引for,它可以使用“索引+1”来检查下一行),然后我会做这样的事情来保留每一行进行一次迭代,并有效地跟踪我对当前行的视图一个周期:

DataRow cachedRow = null;

foreach(var row in MyTable.Rows)
{
    if (cachedRow != null)
    {
        var currentRow = cachedRow;
        var nextRow = row; 
        
        // Do whatever you want with these two rows

    }
    cachedRow = row;
}
// Don't forget to also check the final row (cachedRow) here

请注意,某些迭代器会循环并 return 每次迭代都会 同一对象 的变异。在这种情况下,您需要确保在设置 cachedRow.

时进行深拷贝

您可以进行自定义枚举:

static class Extensions
{
    public static IEnumerable<(T current, T? next)> WithNext<T>(this IEnumerable<T> enumerable)
    {
        using var enumerator = enumerable.GetEnumerator();
        if(!enumerator.MoveNext()) yield break;
        var current = enumerator.Current;

        // optional:
        //yield return (default, current);

        while (enumerator.MoveNext())
        {
            var next = enumerator.Current;
            yield return (current, next);
            current = next;
        }
        
        // optional:
        //yield return (current, default);
    }
}

以下是它的用法:

    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");
        var ca2021Invoices = invoices.Where(i => i.Date.Year == 2021 && i.State.Contains("CA"));
        foreach (var (thisInvoice, nextInvoice) in ca2021Invoices.WithNext())
        {
            //do your stuff comparing each invoice to the next
        }
    }


    private List<Invoice> ReadInvoiceFile(string path)
    {
        //realistically you would use a 3rd party library to do this
    }