C# Lambda List Distinct寫法(group by ... select first)

因為List<Class>要進行多欄位Distinct時, 需在Class裡Overide Equals 和 GetHashCode, 可以使用下列語法替代。參考這篇

利用Group後, 取得每個Group第一組資料出來, 達到Distinct效果。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. class ClassA
  6. {
  7. public int Property1 { get; set; }
  8. public string Property2 { get; set; }
  9. public double Property3 { get; set; }
  10. public string Property4 { get; set; }
  11. public int Property5 { get; set; }
  12. }
  13.  
  14. class Program
  15. {
  16. static void Main()
  17. {
  18. // 創建一個 List<ClassA> 的範例資料
  19. List<ClassA> listOfClassA = new List<ClassA>
  20. {
  21. new ClassA { Property1 = 1, Property2 = "A", Property3 = 1.1, Property4 = "X", Property5 = 100 },
  22. new ClassA { Property1 = 1, Property2 = "A", Property3 = 1.1, Property4 = "Y", Property5 = 101 },
  23. new ClassA { Property1 = 2, Property2 = "B", Property3 = 2.2, Property4 = "X", Property5 = 102 },
  24. new ClassA { Property1 = 2, Property2 = "B", Property3 = 2.2, Property4 = "Y", Property5 = 103 },
  25. new ClassA { Property1 = 3, Property2 = "C", Property3 = 3.3, Property4 = "Z", Property5 = 104 }
  26. };
  27.  
  28. // 使用 LINQ 進行分組,並取得每個群組的第一個元素
  29. var groupedResults = listOfClassA.GroupBy(a => new { a.Property1, a.Property2, a.Property3 })
  30. .Select(group => group.First());
  31.  
  32. // 輸出結果
  33. foreach (var result in groupedResults)
  34. {
  35. Console.WriteLine($"Property1: {result.Property1}, Property2: {result.Property2}, Property3: {result.Property3}");
  36. }
  37. }
  38. }
  39.  
  40.  


留言

這個網誌中的熱門文章

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

Oracle 工作排程 DBMS_JOB 筆記

Oracle 例外控制(Exception Control)