EKsumic's Blog

let today = new Beginning();

Click the left button to use the catalog.

OR

C#foreach的一個案例

通常情況下,我們可能會在篩選之前或之後使用 if 條件來檢查某些條件是否滿足,然後對符合條件的項目進行操作。

在這段代碼中,foreach 循環不僅僅是遍歷集合 r。它還起到了代替 if 條件的作用,因為篩選過程中只留下符合條件的項目進行處理。

var r = dt.Where(x =>
{
    bool b = false;
    var d1 = d2 = DateTime.Now;

    switch (f)
    {
        case 1:
            // 嘗試將日期格式化為平成年
            b = DateTime.TryParse("X" + x.A, out d1) && DateTime.TryParse("X" + x.A, out d2);
            break;
        case 2:
            // 嘗試將日期格式化為西曆日期
            b = DateTime.TryParse(x.A, out d1) && DateTime.TryParse("2100.6.15", out d2);
            break;
    }

    if (b)
        // 檢查日期條件和特殊代碼
        return (d1 >= d2 && x.B.Length > 0 && x.B != "A1");
    else
        return false;
}).ToArray();

// 遍歷符合條件的項目,並追加錯誤代碼
foreach (var i in r)
    i.C += "456, ";

// 檢查是否取消操作
t.Token.ThrowIfCancellationRequested();

foreach 在這裡能夠代替 if 的關鍵原因是,當集合 r 為空時,foreach 根本不會執行任何操作。

注意:return 在 Where 中的作用是決定每個元素是否應該包含在結果集中。其作用範圍僅限於 Where 方法的 lambda 表達式內部。

This article was last edited at 2024-08-19 10:15:29

Today's comments have reached the limit. If you want to comment, please wait until tomorrow (UTC-Time).

There is 07h31m55s left until you can comment.