C#
パターン2: GroupBy + Select ──キーで一意にする業務系の定番
出典: C# でリストの重複を一意にする3つの書き方(Distinct / GroupBy / HashSet) — パターン2: GroupBy + Select ──キーで一意にする業務系の定番
var customers = new List<Customer>
{
new Customer { Id = 1, Name = "田中", UpdatedAt = new DateTime(2025, 1, 10)},
new Customer { Id = 1, Name = "田中(旧)", UpdatedAt = new DateTime(2024, 6, 1)},
new Customer { Id = 2, Name = "山田", UpdatedAt = new DateTime(2025, 2, 5)},
};
// Idで一意にして「最新のUpdatedAtの1件」を残す
var unique = customers
.GroupBy(c => c.Id)
.Select(g => g.OrderByDescending(c => c.UpdatedAt).First())
.ToList();
//結果: Id=1の田中(最新), Id=2の山田
▸ この snippet は実行結果未収録
▸ 実行結果は未収録です
Source収録記事
この snippet は記事の「パターン2: GroupBy + Select ──キーで一意にする業務系の定番」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。
同じ記事から
10 件using System.Linq; var ids = new List<int> { 1, 2, 2, 3, 3, 3, 4 }; var unique = ids.Distinct().ToList();未収録
パターン1: Distinct ──単純な重複を1行で潰す
#d46d933644a6
public class Customer { public int Id { get; set; } public string Name { get; set; }
▶ 実行可
罠:参照型のリストでDistinctは動かない
#45edb7bbd5f0
//対処A: IEqualityComparer<T>を渡す public class CustomerComparer : IEqualityComparer<Customer> { public bool Equals(Customer x, Customer y)=>未収録
罠:参照型のリストでDistinctは動かない
#8249db6f6321
//対処B:クラス側でIEquatable<Customer>を実装 public class Customer : IEquatable<Customer> { public int Id { get; set; }未収録
罠:参照型のリストでDistinctは動かない
#47f2125f4dac
//顧客ID +取引日で一意にする var unique = transactions .GroupBy(t => new { t.CustomerId, t.TransactionDate }) .Select(g => g.First())未収録
複合キーで一意にしたい時
#d839385e04d1
//単純な重複排除 var ids = new List<int> { 1, 2, 2, 3, 3, 3, 4 }; var unique = new HashSet<int>(ids).ToList(); //結果: [1, 2, 3, 4]未収録
パターン3: HashSet<T> ──大量データ・重複検知に使う
#870822b31320
