using System; using System.Collections.Generic; using System.Text; namespace BitStrap { public static class DictionaryExtensions { public struct GCFreeEnumerator { private Dictionary.Enumerator enumerator; public KeyValuePair Current { get { return enumerator.Current; } } public GCFreeEnumerator(Dictionary collection) { enumerator = collection.GetEnumerator(); } public GCFreeEnumerator GetEnumerator() { return this; } public bool MoveNext() { return enumerator.MoveNext(); } } public static GCFreeEnumerator Each(this Dictionary collection) { return new GCFreeEnumerator(collection); } public static int Count(this Dictionary collection, Predicate> predicate) { if (predicate == null) { return 0; } int num = 0; Dictionary.Enumerator enumerator = collection.GetEnumerator(); while (enumerator.MoveNext()) { if (predicate(enumerator.Current)) { num++; } } return num; } public static bool All(this Dictionary collection, Predicate> predicate) { if (predicate == null) { return false; } Dictionary.Enumerator enumerator = collection.GetEnumerator(); while (enumerator.MoveNext()) { if (!predicate(enumerator.Current)) { return false; } } return true; } public static bool Any(this Dictionary collection, Predicate> predicate) { if (predicate == null) { return false; } Dictionary.Enumerator enumerator = collection.GetEnumerator(); while (enumerator.MoveNext()) { if (predicate(enumerator.Current)) { return true; } } return false; } public static KeyValuePair FirstOrDefault(this Dictionary collection) { Dictionary.Enumerator enumerator = collection.GetEnumerator(); if (enumerator.MoveNext()) { return enumerator.Current; } return default(KeyValuePair); } public static KeyValuePair FirstOrDefault(this Dictionary collection, Predicate> predicate) { Dictionary.Enumerator enumerator = collection.GetEnumerator(); while (enumerator.MoveNext()) { if (predicate(enumerator.Current)) { return enumerator.Current; } } return default(KeyValuePair); } public static string ToStringFull(this Dictionary collection) { if (collection == null) { return "null"; } if (collection.Count <= 0) { return "{}"; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("{ "); Dictionary.Enumerator enumerator = collection.GetEnumerator(); while (enumerator.MoveNext()) { stringBuilder.Append(enumerator.Current.Key.ToString()); stringBuilder.Append("="); stringBuilder.Append(enumerator.Current.Value.ToString()); stringBuilder.Append(", "); } stringBuilder.Remove(stringBuilder.Length - 2, 2); stringBuilder.Append(" }"); return stringBuilder.ToString(); } } }