1public class IDList
2{3// MyHashSet<ID> list; の様にしたい4 List<ID> list;5 public IDList()6{7 list = new List<ID>();8}9 public bool Add(ID id)10{11// このforeachをList内部で処理したい12foreach(var item in list)13{14if(item.value == id.value)15{16return false;17}18}19 list.Add(id);20return true;21}22}23public class ID
24{25 public int value { get;}26 public ID(int v)27{28 value = v;29}30}
1using System;2using System.Collections.Generic;34namespace ConsoleAppHashSet
5{6 internal class Program
7{8staticvoidMain(string[] args)9{10 var hashSet = new HashSet<ID>(new IdComparer());1112 var id1 = new ID(1);13 var id2 = new ID(1);1415 bool result = hashSet.Add(id1);16 Console.WriteLine(result);1718 result = hashSet.Add(id1);19 Console.WriteLine(result);2021 result = hashSet.Add(id2);22 Console.WriteLine(result);23}24}2526 public class ID
27{28 public ID(int value)29{30 this.Value = value;31}3233 public int Value { get; set;}34}3536// Derive from this class to provide a custom implementation of the37// IEqualityComparer<T> generic interface for use with collection38// classes such as the Dictionary<TKey,TValue> generic class, or39// with methods such as List<T>.Sort.40 class IdComparer : EqualityComparer<ID>41{42 public override bool Equals(ID x, ID y)43{44if(Object.ReferenceEquals(x, y))return true;4546if(x is null || y is null)return false;4748return x.Value == y.Value;49}5051// Equals() が true を返した場合 GetHashCode() は比較した52// 両オブジェクトで同じ値を返さなければならない53 public override intGetHashCode(ID id)54{55return id.Value.GetHashCode();56}57}58}