6

基本的にForEach-Loopとして機能するExtensionMethodを実装しました。実装は次のようになります。

public static void ForEach(this ListItemCollection collection, Action<ListItem> act )
{
    foreach (ListItem item in collection)
        act(item);
}

ただし、特定の条件が最初に満たされた後にループを停止するメソッドが必要です。

現在の使用方法は次のとおりです。

ddlProcesses.Items.ForEach(item => item.Selected = item.Value == Request["Process"]?true:false);

これに伴う問題は、DropDownList内にこの要件に一致するアイテムが1つしかないことですが、ループはとにかく終了しています。この問題を解決するための最も醜い方法は何でしょうか。

ありがとう。

4

4 に答える 4

5

Func<ListItem, bool>の代わりに、次のAction<ListItem>値が返されたらループを中断できますtrue

public static void ForEach(this ListItemCollection collection,
    Func<ListItem, bool> func)
{
    foreach (ListItem item in collection) {
        if (func(item)) {
            break;
        }
    }
}

次のように使用できます。

ddlProcesses.Items.ForEach(
    item => item.Selected = (item.Value == Request["Process"]));
于 2011-04-29T10:45:56.537 に答える
2
public static void ForEach(this ListItemCollection collection, Action<ListItem> act )
{
    foreach (ListItem item in collection)
    {
        act(item);
        if(condition) break;
    }
}
于 2011-04-29T10:47:47.813 に答える
1

最初にこれを行います:

IEnumerable<ListItem> e = ddlProcesses.Items.OfType<ListItem>(); // or Cast<ListItem>()

一般的なコレクションを取得します。

次に、独自の汎用拡張メソッドを使用できます

public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
{
    foreach (T item in collection) action(item);
}

public static void ForEach<T>(this IEnumerable<T> collection, Func<T> func)
{
    foreach (T item in collection) if (func(item)) return;
}

とにかく、キャッシュルックアップの結果:

var process = Request["Process"];

e.ForEach(i => i.Selected = i.Value == process);
于 2011-04-29T10:46:12.963 に答える
1

要件は100%明確ではありません。条件に一致するものだけを除いて、すべてのアイテムを処理してfalseに設定する必要がありますか、それとも正しい条件でを検索するだけですか、それとも条件が満たされるまで関数を適用しますか?

  1. 条件が最初に一致したときにのみ、アイテムに対して何かを実行します

    public static void ApplyFirst(this ListItemCollection collection,
                          Action<ListItem> action, Func<ListItem, bool> predicate)
    {
        foreach (ListItem item in collection) 
        {
           if (predicate(item))
           {
               action(item);
               return;
           }
        }
    }
    
  2. 条件が一致するたびにアイテムに何かをする

    public static void ApplyIf(this ListItemCollection collection,
                          Action<ListItem> action, Func<ListItem, bool> predicate)
    {
        foreach (ListItem item in collection) 
        {
           if (predicate(item))
           {
               action(item);
           }
        }
    }
    
  3. 条件が一致するまで、すべてのアイテムに何かをします

    public static void ApplyUntil(this ListItemCollection collection,
                          Action<ListItem> action, Func<ListItem, bool> predicate)
    {
        foreach (ListItem item in collection) 
        {
           action(item);
           if (predicate(item))
           {
               return;
           }
        }
    }
    
于 2011-04-29T11:16:28.803 に答える