extensions/CollectionExtensions.cs
2020-04-08 18:40:10 +02:00

157 lines
6.8 KiB
C#

using Chrosey.Extensions.Helper;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chrosey.Extensions
{
public static class CollectionExtensions
{
private static readonly Lazy<RandomSecureVersion> RandomSecure = new Lazy<RandomSecureVersion>((Func<RandomSecureVersion>)(() => new RandomSecureVersion()));
public static T Get<T>(this Dictionary<string, T> dict, string key) where T : class
{
T obj;
return !dict.TryGetValue(key, out obj) ? default(T) : obj;
}
public static IEnumerable<T> Filter<T>(this IEnumerable<T> collection, NameValueCollection query) where T : class
{
var props = typeof(T).GetProperties().Select(p => p.Name.ToLower());
var commonProps = props.Intersect(query.AllKeys.Select(k => k.ToLower()));
foreach (var condition in commonProps)
{
try
{
var values = query[condition].Split('|');
var predicate = PredicateBuilder.False<T>();
foreach (var value in values)
{
if (value.EndsWith("*") && value.StartsWith("*"))
{
predicate = predicate
.Or(m => m
.GetPropertyValue(condition)
.ToString()
.IndexOf(value.Trim('*'), StringComparison.CurrentCultureIgnoreCase) > -1
);
}
else if (value.EndsWith("*"))
{
predicate = predicate
.Or(m => m
.GetPropertyValue(condition)
.ToString()
.StartsWith(value.Trim('*'), StringComparison.CurrentCultureIgnoreCase)
);
}
else if (value.StartsWith("*"))
{
predicate = predicate
.Or(m => m
.GetPropertyValue(condition)
.ToString()
.EndsWith(value.Trim('*'), StringComparison.CurrentCultureIgnoreCase)
);
}
else
{
predicate = predicate
.Or(m => m
.GetPropertyValue(condition)
.ToString()
.Equals(value, StringComparison.CurrentCultureIgnoreCase)
);
}
}
collection = collection.AsQueryable().Where(predicate);
}
catch (NotFoundException)
{
}
}
return collection;
}
public static IOrderedEnumerable<T> Sort<T>(this IEnumerable<T> collection, NameValueCollection query, string defaultSortProperty = "") where T : class
{
if (string.IsNullOrEmpty(query["sort"]))
{
if (!string.IsNullOrEmpty(defaultSortProperty) && collection.First().HasProperty(defaultSortProperty))
{
return collection.OrderBy(c => c.GetPropertyValue(defaultSortProperty));
}
return collection.OrderBy(i => i);
}
var order = query["sort"].Split(',');
var sortProps = order.Select(o => o.Split(' ')[0].ToLower());
var props = typeof(T).GetProperties().Select(p => p.Name.ToLower());
IOrderedEnumerable<T> ordered = null;
foreach (var condition in sortProps.Intersect(props))
{
var isDescending = order
.Single(c => c.StartsWith(condition, StringComparison.CurrentCultureIgnoreCase))
.EndsWith("desc", StringComparison.CurrentCultureIgnoreCase);
if (ordered == null)
{
ordered = isDescending
? collection.OrderByDescending(i => i.GetPropertyValue(condition))
: collection.OrderBy(i => i.GetPropertyValue(condition));
}
else
{
ordered = isDescending
? ordered.ThenByDescending(i => i.GetPropertyValue(condition))
: ordered.ThenBy(i => i.GetPropertyValue(condition));
}
}
return ordered;
}
public static IEnumerable<IGrouping<object, T>> GroupBy<T>(this IEnumerable<T> collection, NameValueCollection query) where T : class
{
var props = typeof(T).GetProperties().Select(p => p.Name.ToLower());
var groupBy = string.IsNullOrEmpty(query["groupby"]) ? "" : query["groupby"].ToLower();
var entferneAb = string.IsNullOrEmpty(query["groupbynletters"]) ? 0 : int.Parse(query["groupbynletters"]);
if (string.IsNullOrEmpty(groupBy) || !props.Contains(groupBy))
{
return collection.GroupBy(i => "Alle " + typeof(T).Name);
}
return entferneAb > 0
? collection.GroupBy(i => i.GetPropertyValue(groupBy).ToString().Remove(Math.Min(entferneAb, i.GetPropertyValue(groupBy).ToString().Length)))
: collection.GroupBy(i => i.GetPropertyValue(groupBy));
}
public static IEnumerable<IGrouping<object, T>> Organize<T>(this IEnumerable<T> collection, NameValueCollection query, string defaultSortProperty = "") where T : class
{
return collection.Filter(query).Sort(query, defaultSortProperty).GroupBy(query);
}
public static string ToQueryString(this IEnumerable<KeyValuePair<string, string>> me)
{
return string.Join("&", me.Select<KeyValuePair<string, string>, string>((Func<KeyValuePair<string, string>, string>)(x => x.Key + "=" + x.Value)));
}
public static IEnumerable<T> ShuffleSecure<T>(this IEnumerable<T> source)
{
T[] sourceArray = source.ToArray<T>();
for (int counter = 0; counter < sourceArray.Length; ++counter)
{
int randomIndex = CollectionExtensions.RandomSecure.Value.Next(counter, sourceArray.Length);
yield return sourceArray[randomIndex];
sourceArray[randomIndex] = sourceArray[counter];
}
}
}
}