Weird Duplicate Comparison

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
					
public class Program
{
	public static void Main()
	{
	var fooArray = new List<Foo>()
	{
		new Foo
		{
			valueOne = "Equal Value",
			valueTwo = "Some value"
		},
		new Foo
		{
			valueOne = "Equal Value",
			valueTwo = "Different value"
		},
		new Foo
		{
			valueOne = "Equal Value",
			valueTwo = null
		},
		new Foo
		{
			valueOne = "SomeOtherValue",
			valueTwo = "whatever"
		},
		new Foo
		{
			valueOne = "I have null value, but should still be in list",
			valueTwo = null
		}
	};
	
	var fooResult = fooArray.Distinct();
	
	fooResult.Dump();
	}
}


public class Foo : IEquatable<Foo>
{
	public string valueOne;
	public string valueTwo;
	public int Code { get; set;}

	public bool Equals(Foo other)
	{
		if(other == null)
		{
			return false;
		}
		if(this.valueOne == other.valueOne && this.valueTwo == (other.valueTwo ?? this.valueTwo))
		{
			return true;
		}
		return false;
	}
	
	public override int GetHashCode()
	{
		int hashCode = Code.GetHashCode();
		
		return hashCode;
	}
}
;