.NET:ForEach()扩展方法和Dictionary [英] .NET: ForEach() extension methods and Dictionary

查看:97
本文介绍了.NET:ForEach()扩展方法和Dictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个快速的问题:我做了很多的Dictionary.Value集合的迭代,并且在惹恼我,我必须调用.ToList()然后可以调用.ForEach(),因为它似乎没有一个可枚举字典中的集合(字典本身,密钥集合或值集合)具有ForEach扩展方法。



有没有什么好的理由为什么ForEach()扩展方法还没有在这些集合上实现,还是只是MS觉得不重要?



在Dictionary集合中迭代是不常见的吗?在存储从数据库中提取的数据时,使用记录标识值作为密钥,我经常使用字典而不是列表。我不得不承认很多时候我甚至没有通过Id键查找,但这只是一个习惯,我已经进入...

解决方案

Eric Lippert解释为什么Microsoft没有写一个 ForEach 扩展方法



你可以自己写一个: p>

  public static void ForEach< T>(此IEnumerable< T>序列,Action< T>动作){
if sequence == null)throw new ArgumentNullException(sequence);
if(action == null)throw new ArgumentNullException(action);
foreach(T项目顺序)
动作(item);
}

//返回false以停止循环
public static void ForEach< T>(此IEnumerable< T>序列,Func< T,bool> action){
if(sequence == null)throw new ArgumentNullException(sequence);
if(action == null)throw new ArgumentNullException(action);

foreach(序列中的T项)
if(!action(item))
return;
}


I have a quick question: I do alot of iteration of Dictionary.Value collections and in annoys me that I have to call .ToList() to then be able to call .ForEach(), as it seems none of the enumerable collections in a Dictionary (The Dictionary itself, the Keys collection or the Values collection) have a ForEach extension method.

Is there any good reason why the ForEach() extension method has not been implemented on these collections, or is it just something that MS felt was not important?

Is it that unusual to iterate over Dictionary collections? I often use Dictionaries rather than Lists when storing data pulled out of Databases, using the records Identity value as the Key. I have to admit alot of the time I don't even lookup by the Id key, but it is just a habit I have gotten into...

解决方案

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

You can write one yourself:

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;
}

这篇关于.NET:ForEach()扩展方法和Dictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆