moved more utilities

This commit is contained in:
Shannon
2019-05-20 16:54:20 +02:00
parent 04b319ecb2
commit 1f70e67ac1
12 changed files with 46 additions and 68 deletions

View File

@@ -1,60 +0,0 @@
using System;
using System.Collections.Generic;
namespace Umbraco.Core
{
/// <summary>
/// A custom equality comparer that excepts a delegate to do the comparison operation
/// </summary>
/// <typeparam name="T"></typeparam>
public class DelegateEqualityComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, T, bool> _equals;
private readonly Func<T, int> _getHashcode;
#region Implementation of IEqualityComparer<in T>
public DelegateEqualityComparer(Func<T, T, bool> equals, Func<T, int> getHashcode)
{
_getHashcode = getHashcode;
_equals = equals;
}
public static DelegateEqualityComparer<T> CompareMember<TMember>(Func<T, TMember> memberExpression) where TMember : IEquatable<TMember>
{
return new DelegateEqualityComparer<T>(
(x, y) => memberExpression.Invoke(x).Equals((TMember)memberExpression.Invoke(y)),
x =>
{
var invoked = memberExpression.Invoke(x);
return !ReferenceEquals(invoked, default(TMember)) ? invoked.GetHashCode() : 0;
});
}
/// <summary>
/// Determines whether the specified objects are equal.
/// </summary>
/// <returns>
/// true if the specified objects are equal; otherwise, false.
/// </returns>
/// <param name="x">The first object of type <paramref name="T"/> to compare.</param><param name="y">The second object of type <paramref name="T"/> to compare.</param>
public bool Equals(T x, T y)
{
return _equals.Invoke(x, y);
}
/// <summary>
/// Returns a hash code for the specified object.
/// </summary>
/// <returns>
/// A hash code for the specified object.
/// </returns>
/// <param name="obj">The <see cref="T:System.Object"/> for which a hash code is to be returned.</param><exception cref="T:System.ArgumentNullException">The type of <paramref name="obj"/> is a reference type and <paramref name="obj"/> is null.</exception>
public int GetHashCode(T obj)
{
return _getHashcode.Invoke(obj);
}
#endregion
}
}

View File

@@ -1,359 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
namespace Umbraco.Core
{
///<summary>
/// Extensions for enumerable sources
///</summary>
public static class EnumerableExtensions
{
internal static bool HasDuplicates<T>(this IEnumerable<T> items, bool includeNull)
{
var hs = new HashSet<T>();
foreach (var item in items)
{
if ((item != null || includeNull) && !hs.Add(item))
return true;
}
return false;
}
/// <summary>
/// Wraps this object instance into an IEnumerable{T} consisting of a single item.
/// </summary>
/// <typeparam name="T"> Type of the object. </typeparam>
/// <param name="item"> The instance that will be wrapped. </param>
/// <returns> An IEnumerable{T} consisting of a single item. </returns>
public static IEnumerable<T> Yield<T>(this T item)
{
// see EnumeratorBenchmarks - this is faster, and allocates less, than returning an array
yield return item;
}
public static IEnumerable<IEnumerable<T>> InGroupsOf<T>(this IEnumerable<T> source, int groupSize)
{
if (source == null)
throw new ArgumentNullException("source");
if (groupSize <= 0)
throw new ArgumentException("Must be greater than zero.", "groupSize");
// following code derived from MoreLinq and does not allocate bazillions of tuples
T[] temp = null;
var count = 0;
foreach (var item in source)
{
if (temp == null) temp = new T[groupSize];
temp[count++] = item;
if (count != groupSize) continue;
yield return temp/*.Select(x => x)*/;
temp = null;
count = 0;
}
if (temp != null && count > 0)
yield return temp.Take(count);
}
public static IEnumerable<TResult> SelectByGroups<TResult, TSource>(this IEnumerable<TSource> source, Func<IEnumerable<TSource>, IEnumerable<TResult>> selector, int groupSize)
{
// don't want to use a SelectMany(x => x) here - isn't this better?
// ReSharper disable once LoopCanBeConvertedToQuery
foreach (var resultGroup in source.InGroupsOf(groupSize).Select(selector))
foreach (var result in resultGroup)
yield return result;
}
/// <summary>The distinct by.</summary>
/// <param name="source">The source.</param>
/// <param name="keySelector">The key selector.</param>
/// <typeparam name="TSource">Source type</typeparam>
/// <typeparam name="TKey">Key type</typeparam>
/// <returns>the unique list</returns>
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
where TKey : IEquatable<TKey>
{
return source.Distinct(DelegateEqualityComparer<TSource>.CompareMember(keySelector));
}
/// <summary>
/// Returns a sequence of length <paramref name="count"/> whose elements are the result of invoking <paramref name="factory"/>.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="factory">The factory.</param>
/// <param name="count">The count.</param>
/// <returns></returns>
public static IEnumerable<T> Range<T>(Func<int, T> factory, int count)
{
for (int i = 1; i <= count; i++)
{
yield return factory.Invoke(i - 1);
}
}
/// <summary>The if not null.</summary>
/// <param name="items">The items.</param>
/// <param name="action">The action.</param>
/// <typeparam name="TItem">The type</typeparam>
public static void IfNotNull<TItem>(this IEnumerable<TItem> items, Action<TItem> action) where TItem : class
{
if (items != null)
{
foreach (TItem item in items)
{
item.IfNotNull(action);
}
}
}
/// <summary>
/// Returns true if all items in the other collection exist in this collection
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="source"></param>
/// <param name="other"></param>
/// <returns></returns>
public static bool ContainsAll<TSource>(this IEnumerable<TSource> source, IEnumerable<TSource> other)
{
if (source == null) throw new ArgumentNullException("source");
if (other == null) throw new ArgumentNullException("other");
return other.Except(source).Any() == false;
}
/// <summary>
/// Returns true if the source contains any of the items in the other list
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <param name="source"></param>
/// <param name="other"></param>
/// <returns></returns>
public static bool ContainsAny<TSource>(this IEnumerable<TSource> source, IEnumerable<TSource> other)
{
return other.Any(source.Contains);
}
/// <summary>
/// Removes all matching items from an <see cref="IList{T}"/>.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">The list.</param>
/// <param name="predicate">The predicate.</param>
/// <remarks></remarks>
public static void RemoveAll<T>(this IList<T> list, Func<T, bool> predicate)
{
for (var i = 0; i < list.Count; i++)
{
if (predicate(list[i]))
{
list.RemoveAt(i--);
}
}
}
/// <summary>
/// Removes all matching items from an <see cref="ICollection{T}"/>.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">The list.</param>
/// <param name="predicate">The predicate.</param>
/// <remarks></remarks>
public static void RemoveAll<T>(this ICollection<T> list, Func<T, bool> predicate)
{
var matches = list.Where(predicate).ToArray();
foreach (var match in matches)
{
list.Remove(match);
}
}
public static IEnumerable<TSource> SelectRecursive<TSource>(
this IEnumerable<TSource> source,
Func<TSource, IEnumerable<TSource>> recursiveSelector, int maxRecusionDepth = 100)
{
var stack = new Stack<IEnumerator<TSource>>();
stack.Push(source.GetEnumerator());
try
{
while (stack.Count > 0)
{
if (stack.Count > maxRecusionDepth)
throw new InvalidOperationException("Maximum recursion depth reached of " + maxRecusionDepth);
if (stack.Peek().MoveNext())
{
var current = stack.Peek().Current;
yield return current;
stack.Push(recursiveSelector(current).GetEnumerator());
}
else
{
stack.Pop().Dispose();
}
}
}
finally
{
while (stack.Count > 0)
{
stack.Pop().Dispose();
}
}
}
/// <summary>
/// Filters a sequence of values to ignore those which are null.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="coll">The coll.</param>
/// <returns></returns>
/// <remarks></remarks>
public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> coll) where T : class
{
return coll.Where(x => x != null);
}
public static IEnumerable<TBase> ForAllThatAre<TBase, TActual>(this IEnumerable<TBase> sequence, Action<TActual> projection)
where TActual : class
{
return sequence.Select(
x =>
{
if (x is TActual)
{
var casted = x as TActual;
projection.Invoke(casted);
}
return x;
});
}
/// <summary>
/// Finds the index of the first item matching an expression in an enumerable.
/// </summary>
/// <typeparam name="T">The type of the enumerated objects.</typeparam>
/// <param name="items">The enumerable to search.</param>
/// <param name="predicate">The expression to test the items against.</param>
/// <returns>The index of the first matching item, or -1.</returns>
public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate)
{
return FindIndex(items, 0, predicate);
}
/// <summary>
/// Finds the index of the first item matching an expression in an enumerable.
/// </summary>
/// <typeparam name="T">The type of the enumerated objects.</typeparam>
/// <param name="items">The enumerable to search.</param>
/// <param name="startIndex">The index to start at.</param>
/// <param name="predicate">The expression to test the items against.</param>
/// <returns>The index of the first matching item, or -1.</returns>
public static int FindIndex<T>(this IEnumerable<T> items, int startIndex, Func<T, bool> predicate)
{
if (items == null) throw new ArgumentNullException("items");
if (predicate == null) throw new ArgumentNullException("predicate");
if (startIndex < 0) throw new ArgumentOutOfRangeException("startIndex");
var index = startIndex;
if (index > 0)
items = items.Skip(index);
foreach (var item in items)
{
if (predicate(item)) return index;
index++;
}
return -1;
}
///<summary>Finds the index of the first occurrence of an item in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="item">The item to find.</param>
///<returns>The index of the first matching item, or -1 if the item was not found.</returns>
public static int IndexOf<T>(this IEnumerable<T> items, T item)
{
return items.FindIndex(i => EqualityComparer<T>.Default.Equals(item, i));
}
/// <summary>
/// Determines if 2 lists have equal elements within them regardless of how they are sorted
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="other"></param>
/// <returns></returns>
/// <remarks>
/// The logic for this is taken from:
/// http://stackoverflow.com/questions/4576723/test-whether-two-ienumerablet-have-the-same-values-with-the-same-frequencies
///
/// There's a few answers, this one seems the best for it's simplicity and based on the comment of Eamon
/// </remarks>
public static bool UnsortedSequenceEqual<T>(this IEnumerable<T> source, IEnumerable<T> other)
{
if (source == null && other == null) return true;
if (source == null || other == null) return false;
var list1Groups = source.ToLookup(i => i);
var list2Groups = other.ToLookup(i => i);
return list1Groups.Count == list2Groups.Count
&& list1Groups.All(g => g.Count() == list2Groups[g.Key].Count());
}
/// <summary>
/// Transforms an enumerable.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="transform"></param>
/// <returns></returns>
public static IEnumerable<TTarget> Transform<TSource, TTarget>(this IEnumerable<TSource> source, Func<IEnumerable<TSource>, IEnumerable<TTarget>> transform)
{
return transform(source);
}
/// <summary>
/// Gets a null IEnumerable as an empty IEnumerable.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <returns></returns>
public static IEnumerable<T> EmptyNull<T>(this IEnumerable<T> items)
{
return items ?? Enumerable.Empty<T>();
}
// the .OfType<T>() filter is nice when there's only one type
// this is to support filtering with multiple types
public static IEnumerable<T> OfTypes<T>(this IEnumerable<T> contents, params Type[] types)
{
return contents.Where(x => types.Contains(x.GetType()));
}
public static IEnumerable<T> SkipLast<T>(this IEnumerable<T> source)
{
using (var e = source.GetEnumerator())
{
if (e.MoveNext() == false) yield break;
for (var value = e.Current; e.MoveNext(); value = e.Current)
yield return value;
}
}
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Direction sortOrder)
{
return sortOrder == Direction.Ascending ? source.OrderBy(keySelector) : source.OrderByDescending(keySelector);
}
}
}

View File

@@ -1,67 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Umbraco.Core
{
/// <summary>
/// Extension methods for 'If' checking like checking If something is null or not null
/// </summary>
public static class IfExtensions
{
/// <summary>The if not null.</summary>
/// <param name="item">The item.</param>
/// <param name="action">The action.</param>
/// <typeparam name="TItem">The type</typeparam>
public static void IfNotNull<TItem>(this TItem item, Action<TItem> action) where TItem : class
{
if (item != null)
{
action(item);
}
}
/// <summary>The if true.</summary>
/// <param name="predicate">The predicate.</param>
/// <param name="action">The action.</param>
public static void IfTrue(this bool predicate, Action action)
{
if (predicate)
{
action();
}
}
/// <summary>
/// Checks if the item is not null, and if so returns an action on that item, or a default value
/// </summary>
/// <typeparam name="TResult">the result type</typeparam>
/// <typeparam name="TItem">The type</typeparam>
/// <param name="item">The item.</param>
/// <param name="action">The action.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
public static TResult IfNotNull<TResult, TItem>(this TItem item, Func<TItem, TResult> action, TResult defaultValue = default(TResult))
where TItem : class
{
return item != null ? action(item) : defaultValue;
}
/// <summary>
/// Checks if the value is null, if it is it returns the value specified, otherwise returns the non-null value
/// </summary>
/// <typeparam name="TItem"></typeparam>
/// <param name="item"></param>
/// <param name="action"></param>
/// <returns></returns>
public static TItem IfNull<TItem>(this TItem item, Func<TItem, TItem> action)
where TItem : class
{
return item ?? action(item);
}
}
}

View File

@@ -1,50 +0,0 @@
using System;
using System.Collections.Generic;
namespace Umbraco.Core
{
/// <summary>
/// Provides extensions to the List type.
/// </summary>
internal static class ListExtensions
{
// based upon the original Zip<T1, T2, TResult> method
public static IEnumerable<TResult> Zip<T1, T2, T3, TResult>(this IEnumerable<T1> e1, IEnumerable<T2> e2, IEnumerable<T3> e3,
Func<T1, T2, T3, TResult> resultSelector)
{
if (e1 == null) throw new ArgumentNullException("e1");
if (e2 == null) throw new ArgumentNullException("e2");
if (e3 == null) throw new ArgumentNullException("e3");
if (resultSelector == null) throw new ArgumentNullException("resultSelector");
return ZipIterator(e1, e2, e3, resultSelector);
}
private static IEnumerable<TResult> ZipIterator<T1, T2,T3, TResult>(IEnumerable<T1> ie1, IEnumerable<T2> ie2, IEnumerable<T3> ie3,
Func<T1, T2, T3, TResult> resultSelector)
{
var e1 = ie1.GetEnumerator();
try
{
var e2 = ie2.GetEnumerator();
var e3 = ie3.GetEnumerator();
try
{
while (e1.MoveNext() && e2.MoveNext() && e3.MoveNext())
yield return resultSelector(e1.Current, e2.Current, e3.Current);
}
finally
{
if (e2 != null)
e2.Dispose();
if (e3 != null)
e3.Dispose();
}
}
finally
{
if (e1 != null)
e1.Dispose();
}
}
}
}

View File

@@ -1,8 +0,0 @@
namespace Umbraco.Core.Persistence.DatabaseModelDefinitions
{
public enum Direction
{
Ascending = 0,
Descending = 1
}
}

View File

@@ -560,7 +560,6 @@
<Compile Include="DataTableExtensions.cs" />
<Compile Include="DateTimeExtensions.cs" />
<Compile Include="DecimalExtensions.cs" />
<Compile Include="DelegateEqualityComparer.cs" />
<Compile Include="DelegateExtensions.cs" />
<Compile Include="Deploy\ArtifactBase.cs" />
<Compile Include="Deploy\ArtifactDependency.cs" />
@@ -590,7 +589,6 @@
<Compile Include="Dictionary\ICultureDictionaryFactory.cs" />
<Compile Include="Logging\DisposableTimer.cs" />
<Compile Include="EmailSender.cs" />
<Compile Include="EnumerableExtensions.cs" />
<Compile Include="Events\CancellableEventArgs.cs" />
<Compile Include="Events\CancellableObjectEventArgs.cs" />
<Compile Include="Events\ContentCacheEventArgs.cs" />
@@ -651,7 +649,6 @@
<Compile Include="HttpContextExtensions.cs" />
<Compile Include="IDisposeOnRequestEnd.cs" />
<Compile Include="IEmailSender.cs" />
<Compile Include="IfExtensions.cs" />
<Compile Include="IntExtensions.cs" />
<Compile Include="IO\FileSecurityException.cs" />
<Compile Include="IO\FileSystemExtensions.cs" />
@@ -670,7 +667,6 @@
<Compile Include="IRuntime.cs" />
<Compile Include="IRuntimeState.cs" />
<Compile Include="LambdaExpressionCacheKey.cs" />
<Compile Include="ListExtensions.cs" />
<Compile Include="Logging\DebugDiagnosticsLogger.cs" />
<Compile Include="Logging\ILogger.cs" />
<Compile Include="Logging\IProfiler.cs" />
@@ -941,7 +937,6 @@
<Compile Include="Persistence\DatabaseModelDefinitions\DbIndexDefinition.cs" />
<Compile Include="Persistence\DatabaseModelDefinitions\DefinitionFactory.cs" />
<Compile Include="Persistence\DatabaseModelDefinitions\DeletionDataDefinition.cs" />
<Compile Include="Persistence\DatabaseModelDefinitions\Direction.cs" />
<Compile Include="Persistence\DatabaseModelDefinitions\ForeignKeyDefinition.cs" />
<Compile Include="Persistence\DatabaseModelDefinitions\IndexColumnDefinition.cs" />
<Compile Include="Persistence\DatabaseModelDefinitions\IndexDefinition.cs" />