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

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

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

using System;
using System.Collections.Generic;
using System.Linq;

class ClassA
{
    public int Property1 { get; set; }
    public string Property2 { get; set; }
    public double Property3 { get; set; }
    public string Property4 { get; set; }
    public int Property5 { get; set; }
}

class Program
{
    static void Main()
    {
        // 創建一個 List<ClassA> 的範例資料
        List<ClassA> listOfClassA = new List<ClassA>
        {
            new ClassA { Property1 = 1, Property2 = "A", Property3 = 1.1, Property4 = "X", Property5 = 100 },
            new ClassA { Property1 = 1, Property2 = "A", Property3 = 1.1, Property4 = "Y", Property5 = 101 },
            new ClassA { Property1 = 2, Property2 = "B", Property3 = 2.2, Property4 = "X", Property5 = 102 },
            new ClassA { Property1 = 2, Property2 = "B", Property3 = 2.2, Property4 = "Y", Property5 = 103 },
            new ClassA { Property1 = 3, Property2 = "C", Property3 = 3.3, Property4 = "Z", Property5 = 104 }
        };

        // 使用 LINQ 進行分組,並取得每個群組的第一個元素
        var groupedResults = listOfClassA.GroupBy(a => new { a.Property1, a.Property2, a.Property3 })
                                         .Select(group => group.First());

        // 輸出結果
        foreach (var result in groupedResults)
        {
            Console.WriteLine($"Property1: {result.Property1}, Property2: {result.Property2}, Property3: {result.Property3}");
        }
    }
}



留言

這個網誌中的熱門文章

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

Oracle 例外控制(Exception Control)

Oracle 工作排程 DBMS_JOB 筆記