DistinctExtensions.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Npoi.Mapper;
  6. namespace JiaZhiQuan.Common.Utils.Extend {
  7. public static class DistinctExtensions {
  8. public static IEnumerable<T> Distinct<T, V>(this IEnumerable<T> source, Func<T, V> keySelector) =>
  9. source.Distinct(new CommonEqualityComparer<T, V>(keySelector));
  10. }
  11. public static class IEnumerableExtension {
  12. public static List<T> BlockDeal<S, T>(this IEnumerable<S> source, Func<IEnumerable<S>, T> deal,
  13. int startBlockNum = 0, int blockSize = 100) {
  14. List<T> result = new List<T>();
  15. if (source == null || source.Count() == 0) return result;
  16. int startNum = startBlockNum * blockSize;
  17. int count = source.Count();
  18. while (startNum < count) {
  19. int size = count - startNum > blockSize ? blockSize : count - startNum;
  20. IEnumerable<S> dealList = source.Skip(startNum).Take(size);
  21. result.Add(deal(dealList));
  22. startNum += size;
  23. }
  24. return result;
  25. }
  26. public static async Task<List<T>> BlockDealAsync<S, T>(this IEnumerable<S> source,
  27. Func<IEnumerable<S>, Task<T>> deal, int startBlockNum = 0, int blockSize = 100) {
  28. List<T> result = new List<T>();
  29. if (source == null || source.Count() == 0) return result;
  30. int startNum = startBlockNum * blockSize;
  31. int count = source.Count();
  32. while (startNum < count) {
  33. int size = count - startNum > blockSize ? blockSize : count - startNum;
  34. IEnumerable<S> dealList = source.Skip(startNum).Take(size);
  35. result.Add(await deal(dealList));
  36. startNum += size;
  37. }
  38. return result;
  39. }
  40. }
  41. public class CommonEqualityComparer<T, V> : IEqualityComparer<T> {
  42. private readonly Func<T, V> keySelector;
  43. public CommonEqualityComparer(Func<T, V> keySelector) {
  44. this.keySelector = keySelector;
  45. }
  46. public bool Equals(T x, T y) {
  47. return EqualityComparer<V>.Default.Equals(keySelector(x), keySelector(y));
  48. }
  49. public int GetHashCode(T obj) {
  50. return EqualityComparer<V>.Default.GetHashCode(keySelector(obj));
  51. }
  52. }
  53. }