.NET:ForEach()扩展方法和Dictionary

时间:2009-08-26 01:36:40

标签: dictionary foreach

我有一个简单的问题:我对Dictionary.Value集合进行了很多迭代,并且让我感到烦恼,我必须调用.ToList()然后才能调用.ForEach(),因为它似乎没有可枚举的字典中的集合(字典本身,Keys集合或Values集合)具有ForEach扩展方法。

为什么没有在这些集合上实现ForEach()扩展方法,或者它只是MS认为不重要的东西?

迭代字典集合是不寻常的吗?当存储从数据库中提取的数据时,我经常使用字典而不是列表,使用记录标识值作为密钥。我不得不承认我甚至没有用Id键查找的时间,但这只是我习惯的习惯......

3 个答案:

答案 0 :(得分:8)

Eric Lippert explains why Microsoft didn't write a ForEach extension method

你可以自己写一个:

public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action) {
    if (sequence == null) throw new ArgumentNullException("sequence");
    if (action == null) throw new ArgumentNullException("action");
    foreach(T item in sequence) 
        action(item);
}

//Return false to stop the loop
public static void ForEach<T>(this IEnumerable<T> sequence, Func<T, bool> action) {
    if (sequence == null) throw new ArgumentNullException("sequence");
    if (action == null) throw new ArgumentNullException("action");

    foreach(T item in sequence) 
        if (!action(item))
            return;
}

答案 1 :(得分:2)

嗯,我们将我的评论升级为答案,因此我可以包含可读代码。

Eric对ForEach上的一般IEnumerable<>提出了一个很好的论据,但对于Dictionary<>,它仍然是有利的,因为普通的foreach循环会给你KeyValuePair 1}},但lambda可以有两个参数,一个用于键,一个用于值,这将使代码看起来更清晰。

public static void ForEach<TKey, TValue>(this Dictionary<TKey, TValue> dict, Action<TKey, TValue> action) {
    if (dict == null) throw new ArgumentNullException("dict");
    if (action == null) throw new ArgumentNullException("action");

    foreach (KeyValuePair<TKey, TValue> item in dict) {
        action(item.Key, item.Value);
    }
}

答案 2 :(得分:1)

没有充分理由(IMO)没有在IEnumerable&lt; T&gt;上实现ForEach扩展方法。 (相反,它只在List&lt; T&gt;上)。我在我的公共库中创建了一个ForEach扩展方法,它只有几行代码。

public static void ForEach<T>( this IEnumerable<T> list, Action<T> action ) {
    foreach( var o in list ) {
        action( o );
    }
}