using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
namespace Muchinfo.PC.Common.Extensions
{
public static class EnumerableExtensions
{
///
/// To the observable collection.
///
///
/// The source.
/// ObservableCollection{``0}.
public static ObservableCollection ToObservableCollection(this IEnumerable source)
{
return source == null ? null : new ObservableCollection(source);
}
///
/// Order By 扩展
///
///
/// The list.
/// The sort field.
/// The sort direction.
/// IEnumerable{``0}.
public static IEnumerable OrderBy(this IEnumerable list, string sortField, string sortDirection = "asc")
{
try
{
if (string.IsNullOrWhiteSpace(sortField.Trim())) return list;
PropertyInfo prop = typeof(T).GetProperty(sortField.Trim());
if (prop == null)
{
return list;
}
var descending = sortDirection.Trim().ToLower() == "desc";
return descending ? list.OrderByDescending(x => prop.GetValue(x, null)) : list.OrderBy(x => prop.GetValue(x, null));
}
catch
{
return list;
}
}
}
}