IEqualityComparer implementation

CSharp · Console

/Program.cs

using System;
using System.Linq;
using System.Collections.Generic;
					
public class Program
{
	// test class
	public class StudentTestData {
		public string AccessionNumber { get;set; }
		public string LoginId { get; set; }
	}
	
	// Custom comparer taking generic input parameter and a delegate function to do matching
	public class CustomComparer<T> : IEqualityComparer<T> {
		private readonly Func<T, object> _match;
		
		public CustomComparer(Func<T, object> match) {
			_match = match;
		}
		
		// tries to match both argument its return values against eachother
		public bool Equals(T data1, T data2) {
			return object.Equals(_match(data1), _match(data2));
		}
		
		// overly simplistic implementation
		public int GetHashCode(T data) {
			var matchValue = _match(data);
			if (matchValue == null) {
				return 42.GetHashCode();
			}
			return matchValue.GetHashCode();
		}
	}
	
	public static void Main()
	{
		var data = new List<StudentTestData>() {
			new StudentTestData() {
				AccessionNumber = "A1",
				LoginId = "L1"
			},
			new StudentTestData() {
				AccessionNumber = "A1",
				LoginId = "L2"
			},
			new StudentTestData() {
				AccessionNumber = "A2",
				LoginId = "L1"
			},
			new StudentTestData() {
				AccessionNumber = "A3",
				LoginId = "L1"
			},
			new StudentTestData() {
				AccessionNumber = "A1",
				LoginId = "L3"
			}
		};
		// compare by access number
		var accessComparer = new CustomComparer<StudentTestData>(d => d.AccessionNumber );
		// compare by login id
		var loginComparer = new CustomComparer<StudentTestData>(d => d.LoginId );
		
		Console.WriteLine("Per accession number");
		// add IEqualityComparer to distinct call
		foreach (var d in data.Distinct( accessComparer )) {
			Console.WriteLine( "{0}, {1}", d.AccessionNumber, d.LoginId);
		}
		Console.WriteLine("Per login number");
		// add IEqualityComparer to distinct call
		foreach (var d in data.Distinct( loginComparer )) {
			Console.WriteLine( "{0}, {1}", d.AccessionNumber, d.LoginId);
		}
	}
}
;