| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Linq;
- using System.Reflection;
- namespace Muchinfo.PC.Common.Extensions
- {
- public static class EnumerableExtensions
- {
- /// <summary>
- /// To the observable collection.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="source">The source.</param>
- /// <returns>ObservableCollection{``0}.</returns>
- public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> source)
- {
- return source == null ? null : new ObservableCollection<T>(source);
- }
- /// <summary>
- /// Order By 扩展
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="list">The list.</param>
- /// <param name="sortField">The sort field.</param>
- /// <param name="sortDirection">The sort direction.</param>
- /// <returns>IEnumerable{``0}.</returns>
- public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> 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;
- }
- }
- }
- }
|