C# 撰寫擴展CLASS - DistinctBy

C# 撰寫擴展CLASS - DistinctBy

  1. void Main()
  2. {
  3. List<ClassA> list = new List<UserQuery.ClassA>();
  4. list.Add(new ClassA() { strA = "A", strB = "A1" });
  5. list.Add(new ClassA() { strA = "B", strB = "B1" });
  6. list.Add(new ClassA() { strA = "B", strB = "C1" });
  7. var a = list.DistinctBy(x => x.strA).ToList();
  8. // strA , strB
  9. // A, A1
  10. // B, B1
  11. var b = list.DistinctBy(x => x.strB).ToList();
  12. // strA , strB
  13. // A, A1
  14. // B, B1
  15. // B, C1
  16. }
  17. public class ClassA
  18. {
  19. public string strA {get;set;}
  20. public string strB {get;set;}
  21. }
  22. //撰寫一個擴展CLASS
  23. public static class DistinctByClass
  24. {
  25. //方法套用在列舉上
  26. public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
  27. {
  28. HashSet<TKey> seenKeys = new HashSet<TKey>();
  29. foreach (TSource element in source)
  30. {
  31. if (seenKeys.Add(keySelector(element)))
  32. {
  33. yield return element;
  34. }
  35. }
  36. }
  37. }

DistinctBy可以直接使用在 list 上, 是因為 DistinctByClass 是一個靜態的擴展CLASS, 由方法DinstinctBy來看, 可以接受 IEnumerable< TSource > 。

 

留言

這個網誌中的熱門文章

ORA-12514: TNS: 監聽器目前不知道連線描述區中要求的服務

Oracle 工作排程 DBMS_JOB 筆記

Oracle 例外控制(Exception Control)