Consider this array
string[] presidents = {
"Adams", "Arthur", "Buchanan", "Bush", "Carter", "Cleveland",
"Clinton", "Coolidge", "Eisenhower", "Fillmore", "Ford", "Garfield",
"Grant", "Harding", "Harrison", "Hayes", "Hoover", "Jackson",
"Jefferson", "Johnson", "Kennedy", "Lincoln", "Madison", "McKinley",
"Monroe", "Nixon", "Pierce", "Polk", "Reagan", "Roosevelt", "Taft",
"Taylor", "Truman", "Tyler", "Van Buren", "Washington", "Wilson"};
My grouping criteria is that the name with length 1 to 5 in one group and remaining in other group.
I implemented this using this derived class
class MyLengthComparer:IEqualityComparer<Int32>
{
public Int32 GetHashCode(Int32 i)
{
return i<=5?1:6;
}
public Boolean Equals(Int32 i1,Int32 i2)
{
if(i1<=5 && i2<=5)
return true;
if(i1>5 && i2>5)
return true;
else
return false;
}
}
Now I run this
IEnumerable<IGrouping<Int32, String>> groupVar = presidents.GroupBy(prez=>prez.Length,new MyLengthComparer());
foreach(IGrouping<Int32, String> grp in groupVar)
{
Console.WriteLine("******" + grp.Key + "******" );
foreach(String name in grp)
Console.WriteLine(name);
}
Console.ReadKey();
I want to know the meaning of the two functions of the IEqualityInterface.I mean how the comparison is actually being done.
What is the significance of Key in IGrouping, why is it showing 5 and 6?