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

MrL*_*ane 2 foreach dictionary

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

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

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

SLa*_*aks 8

Eric Lippert解释了为什么微软没有编写ForEach扩展方法.

你可以自己写一个:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 埃里克的文章提出了一些好处.我希望人们在使用你的答案之前疯狂地阅读它. (2认同)