// (c) Copyright ESRI. // This source is subject to the Microsoft Public License (Ms-PL). // Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details. // All other rights reserved. using System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace ESRI.ArcGIS.Client.Toolkit { /// /// IEnumerable extensions : ToObservableCollection, ForEach, Descendants, Leaves /// internal static class CollectionExtensions { /// /// Converts an enumerable to an observable collection. /// /// The type of objects in the enumeration. /// The enumerable. /// public static ObservableCollection ToObservableCollection(this IEnumerable enumerable) { var observableCollection = new ObservableCollection(); foreach (T item in enumerable) observableCollection.Add(item); return observableCollection; } /// /// Performs the specified action on each element of the enumeration. /// /// The type of objects in the enumeration. /// The enumerable. /// The System.Action delegate to perform on each element of the enumeration. public static void ForEach(this IEnumerable enumerable, System.Action action) { if (enumerable != null) foreach (T item in enumerable) action(item); } /// /// Find all descendants from an enumerable. /// /// The type of objects in the enumeration. /// The enumerable. /// The children delegate. /// public static IEnumerable Descendants(this IEnumerable enumerable, Func> childrenDelegate) { if (enumerable == null) yield break; foreach (T item in enumerable) { yield return item; IEnumerable children = childrenDelegate(item); if (children != null) { foreach (T child in children.Descendants(childrenDelegate)) yield return child; } } } /// /// Find all leaves from an enumerable. /// /// The type of objects in the enumeration. /// The enumerable. /// The children delegate. /// public static IEnumerable Leaves(this IEnumerable enumerable, Func> childrenDelegate) { if (enumerable == null) yield break; foreach (T item in enumerable) { IEnumerable children = childrenDelegate(item); if (children == null) { // it's a leaf yield return item; } else { // not a leaf ==> recursive call foreach (T child in children.Leaves(childrenDelegate)) yield return child; } } } } }