You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
2.2 KiB
70 lines
2.2 KiB
namespace StubAPI;
|
|
|
|
|
|
public static class Extensions
|
|
{
|
|
internal static Task<T?> AddItem<T>(this IList<T> collection, T? item)
|
|
{
|
|
if(item == null || collection.Contains(item))
|
|
{
|
|
return Task.FromResult<T?>(default(T));
|
|
}
|
|
collection.Add(item);
|
|
return Task.FromResult<T?>(item);
|
|
}
|
|
|
|
internal static Task<bool> DeleteItem<T>(this IList<T> collection, T? item)
|
|
{
|
|
if(item == null)
|
|
{
|
|
return Task.FromResult(false);
|
|
}
|
|
bool result = collection.Remove(item!);
|
|
return Task.FromResult(result);
|
|
}
|
|
|
|
internal static Task<T?> UpdateItem<T>(this IList<T> collection, T? oldItem, T? newItem)
|
|
{
|
|
if(oldItem == null || newItem == null) return Task.FromResult<T?>(default(T));
|
|
|
|
if(!collection.Contains(oldItem))
|
|
{
|
|
return Task.FromResult<T?>(default(T));
|
|
}
|
|
|
|
collection.Remove(oldItem!);
|
|
collection.Add(newItem!);
|
|
return Task.FromResult<T?>(newItem);
|
|
}
|
|
|
|
public static IEnumerable<T> GetItemsWithFilterAndOrdering<T>(this IEnumerable<T> list, Func<T, bool> filter, int index, int count, Enum? orderCriterium, bool descending = false ) where T : class
|
|
{
|
|
var filteredList = list.Where(filter);
|
|
|
|
if(orderCriterium != null)
|
|
{
|
|
filteredList = filteredList.OrderByCriteria(orderCriterium, descending);
|
|
}
|
|
return filteredList
|
|
.Skip(index * count)
|
|
.Take(count);
|
|
}
|
|
|
|
public static IOrderedEnumerable<T> OrderByCriteria<T>(this IEnumerable<T> list, Enum orderCriterium, bool descending = false ) where T : class
|
|
{
|
|
var orderCriteriumString = orderCriterium.ToString();
|
|
if (orderCriteriumString.StartsWith("By"))
|
|
{
|
|
orderCriteriumString = orderCriteriumString.Substring(2);
|
|
}
|
|
var propertyInfo = typeof(T).GetProperty(orderCriteriumString);
|
|
if (propertyInfo == null)
|
|
{
|
|
throw new ArgumentException($"No property {orderCriterium} in type {typeof(T)}");
|
|
}
|
|
|
|
return descending ? list.OrderByDescending(x => propertyInfo.GetValue(x)) : list.OrderBy(x => propertyInfo.GetValue(x));
|
|
}
|
|
|
|
|
|
} |