.NET:ForEach()扩展方法和Dictionary [英] .NET: ForEach() extension methods and Dictionary
问题描述
有没有什么好的理由为什么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屋!