using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Tango.Core { public static class Extensions { public static int IndexOf(this IEnumerable source, T item) { var entry = source.Select((x, i) => new { Value = x, Index = i }) .Where(x => object.Equals(x.Value, item)) .FirstOrDefault(); return entry != null ? entry.Index : -1; } public static void CopyTo(this IEnumerable source, T[] array, int startIndex) { int lowerBound = array.GetLowerBound(0); int upperBound = array.GetUpperBound(0); if (startIndex < lowerBound) throw new ArgumentOutOfRangeException("startIndex", "The start index must be greater than or equal to the array lower bound"); if (startIndex > upperBound) throw new ArgumentOutOfRangeException("startIndex", "The start index must be less than or equal to the array upper bound"); int i = 0; foreach (var item in source) { if (startIndex + i > upperBound) throw new ArgumentException("The array capacity is insufficient to copy all items from the source sequence"); array[startIndex + i] = item; i++; } } } public class WeakList : IList { private List> _innerList = new List>(); #region IList Members public int IndexOf(T item) { return _innerList.Select(wr => wr.Target).IndexOf(item); } public void Insert(int index, T item) { _innerList.Insert(index, new WeakReference(item)); } public void RemoveAt(int index) { _innerList.RemoveAt(index); } public T this[int index] { get { return _innerList[index].Target; } set { _innerList[index] = new WeakReference(value); } } #endregion #region ICollection Members public void Add(T item) { _innerList.Add(new WeakReference(item)); } public void Clear() { _innerList.Clear(); } public bool Contains(T item) { return _innerList.Any(wr => object.Equals(wr.Target, item)); } public void CopyTo(T[] array, int arrayIndex) { _innerList.Select(wr => wr.Target).CopyTo(array, arrayIndex); } public int Count { get { return _innerList.Count; } } public bool IsReadOnly { get { return false; } } public bool Remove(T item) { int index = IndexOf(item); if (index > -1) { RemoveAt(index); return true; } return false; } #endregion #region IEnumerable Members public IEnumerator GetEnumerator() { return _innerList.Select(x => x.Target).GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion public void Purge() { _innerList.RemoveAll(wr => !wr.IsAlive); } } [Serializable] public class WeakReference : WeakReference { public WeakReference(T target) : base(target) { } public WeakReference(T target, bool trackResurrection) : base(target, trackResurrection) { } public WeakReference(SerializationInfo info, StreamingContext context) : base(info, context) { } public new T Target { get { return (T)base.Target; } } } }