I believe the following code should generate two instances of the same anonymous type, with properties in the same order, with the same names, types and values.
static void Main(string[] args)
{
var letterFreq1 = CountLetters("aabbbc");
var letterFreq2 = CountLetters("aabbbc");
if (letterFreq1.Equals(letterFreq2))
Console.WriteLine("Is anagram");
else
Console.WriteLine("Is not an anagram");
}
public static object CountLetters(string input) => input.ToCharArray()
.GroupBy(x => x)
.Select(x => new {Letter = x.Key, Count = x.Count()})
.OrderBy(x => x.Letter)
.ToList();
According to MS documentation:
If two or more anonymous object initializers in an assembly specify a sequence of properties that are in the same order and that have the same names and types, the compiler treats the objects as instances of the same type. They share the same compiler-generated type information.
and
Because the Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashCode methods of the properties, two instances of the same anonymous type are equal only if all their properties are equal.
I interpret this as meaning I should get equality on letterFreq1 and letterFreq2, but this isn't occurring. Can anyone identify why the equality check fails please? I'm trying to avoid a manual approach to comparing property values.
This is a similar question but doesn't seen to help solve my issue.
Many thanks.