EnumerableExtensions.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System.Collections.Generic;
  2. using System.Collections.ObjectModel;
  3. using System.Linq;
  4. using System.Reflection;
  5. namespace Muchinfo.PC.Common.Extensions
  6. {
  7. public static class EnumerableExtensions
  8. {
  9. /// <summary>
  10. /// To the observable collection.
  11. /// </summary>
  12. /// <typeparam name="T"></typeparam>
  13. /// <param name="source">The source.</param>
  14. /// <returns>ObservableCollection{``0}.</returns>
  15. public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> source)
  16. {
  17. return source == null ? null : new ObservableCollection<T>(source);
  18. }
  19. /// <summary>
  20. /// Order By 扩展
  21. /// </summary>
  22. /// <typeparam name="T"></typeparam>
  23. /// <param name="list">The list.</param>
  24. /// <param name="sortField">The sort field.</param>
  25. /// <param name="sortDirection">The sort direction.</param>
  26. /// <returns>IEnumerable{``0}.</returns>
  27. public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> list, string sortField, string sortDirection = "asc")
  28. {
  29. try
  30. {
  31. if (string.IsNullOrWhiteSpace(sortField.Trim())) return list;
  32. PropertyInfo prop = typeof(T).GetProperty(sortField.Trim());
  33. if (prop == null)
  34. {
  35. return list;
  36. }
  37. var descending = sortDirection.Trim().ToLower() == "desc";
  38. return descending ? list.OrderByDescending(x => prop.GetValue(x, null)) : list.OrderBy(x => prop.GetValue(x, null));
  39. }
  40. catch
  41. {
  42. return list;
  43. }
  44. }
  45. }
  46. }