2 using System.Collections;
3 using System.Collections.Generic;
6 using System.Linq.Expressions;
8 using System.Text.RegularExpressions;
9 using Pithos.Client.WPF.SelectiveSynch;
11 using Pithos.Interfaces;
13 namespace Pithos.Client.WPF.Utils
15 public static class EnumerableExtensions
17 public static IEnumerable<T> Slice<T>(this IEnumerable<T> collection, int start, int end)
22 if (collection == null)
23 throw new ArgumentNullException("collection");
25 // Optimise item count for ICollection interfaces.
26 if (collection is ICollection<T>)
27 count = ((ICollection<T>)collection).Count;
28 else if (collection is ICollection)
29 count = ((ICollection)collection).Count;
32 count = collection.Count();
35 // Get start/end indexes, negative numbers start at the end of the collection.
42 foreach (var item in collection)
54 public static IEnumerable<Node<T>> ToTree<TSource,T>(this IEnumerable<TSource> enumerable,Func<TSource,string> pathFunc,Func<TSource,T> valueFunc,string delimiter="/")
56 var orderedItems=enumerable.OrderBy(pathFunc);
57 var lookups = new Dictionary<string,Node<T>>();
58 var nodes = new List<Node<T>>();
59 foreach (var item in orderedItems)
61 var path = pathFunc(item);
62 var value = valueFunc(item);
63 var newNode = new Node<T> { Path = path,Data=value };
64 lookups[path] = newNode;
66 var lastIndex = path.LastIndexOf(delimiter, StringComparison.Ordinal);
67 var upTo = lastIndex < 0 ? path.Length - 1 : lastIndex;
68 var parentPath = path.Substring(0, upTo);
71 if (lookups.TryGetValue(parentPath, out parent))
73 parent.Children.Add(newNode);
74 parent.Children.Sort((x,y)=>String.CompareOrdinal(x.Path, y.Path));
86 static readonly Regex PascalCaseRegex = new Regex("[a-z][A-Z]", RegexOptions.Compiled);
87 public static string Name(this Enum value)
89 var name = Enum.GetName(value.GetType(), value);
90 return PascalCaseRegex.Replace(name, m => m.Value[0] + " " + char.ToLower(m.Value[1]));