using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace Muchinfo.MTPClient.Infrastructure.Extensions
{
///
/// QueryableExtensions类
///
public static class QueryableExtensions
{
#region Methods
#region Public Static Methods
///
/// 属性名排序
///
///
/// The queryable.
/// Name of the property.
/// IQueryable{``0}.
public static IQueryable OrderBy(this IQueryable queryable, string propertyName)
{
return QueryableHelper.OrderBy(queryable, propertyName);
}
///
/// 属性名倒排序
///
///
/// The queryable.
/// Name of the property.
/// IQueryable{``0}.
public static IQueryable OrderByDescending(this IQueryable queryable, string propertyName)
{
return QueryableHelper.OrderByDescending(queryable, propertyName);
}
///
/// 数据随机排序
///
/// 泛型类型
/// 源数组
/// 特定数组.
public static T[] ToRandomArray(this T[] source)
{
if (source == null || source.Length == 0)
{
return new T[] { };
}
var dir = new Dictionary();
var rd = new Random(unchecked((int)DateTime.Now.Ticks));
var count = source.Length;
foreach (var value in source)
{
var index = rd.Next(1, count + 1000);
while (dir.Keys.Contains(index))
{
index = rd.Next(1, count + 1000);
}
dir.Add(index, value);
}
return dir.Keys.OrderBy(z => z).Select(key => dir[key]).ToArray();
}
#endregion Public Static Methods
#endregion Methods
#region Nested Types
///
/// QueryableHelper类
///
///
private static class QueryableHelper
{
#region Fields
///
/// The _cache
///
public static Dictionary _cache = new Dictionary();
#endregion Fields
#region Methods
#region Public Static Methods
///
/// Orders the by.
///
/// The queryable.
/// The properytname.
/// IQueryable{`0}.
public static IQueryable OrderBy(IQueryable queryable, string propertyName)
{
dynamic keySelector = GetLambdaExpression(propertyName);
return Queryable.OrderBy(queryable, keySelector);
}
///
/// Orders the by descending.
///
/// The queryable.
/// Name of the properyt.
/// IQueryable{`0}.
public static IQueryable OrderByDescending(IQueryable queryable, string propertyName)
{
dynamic keySelector = GetLambdaExpression(propertyName);
return Queryable.OrderByDescending(queryable, keySelector);
}
#endregion Public Static Methods
#region Private Static Methods
///
/// Gets the lambda expression.
///
/// Name of the property.
/// LambdaExpression.
private static LambdaExpression GetLambdaExpression(string propertyName)
{
if (_cache.ContainsKey(propertyName))
{
return _cache[propertyName];
}
var param = Expression.Parameter(typeof(T));
var body = Expression.Property(param, propertyName);
var keySelector = Expression.Lambda(body, param);
_cache[propertyName] = keySelector;
return keySelector;
}
#endregion Private Static Methods
#endregion Methods
}
#endregion Nested Types
}
}