I am trying to use Linq to convert a list to Dictionary. I have been able to get proper results with anonymous types as keys, but not with concrete types. Please see code snipped below:
// Works. Produces 329 entries in dictionary, as expected.
var groupByMonth =
from e in list
group e by new { e.chk.Month, e.chk.Year } into g
select new { month = g.Key, rates = g.ToList() };
var monnthlyRates = groupByMonth.ToList();
var monnthlyRatesDict = groupByMonth.ToDictionary(t => t.month, t => t.rates);
// IS NOT WORKING. Produces 30K entries in dictionary; same num as in the list.
// i.e. the grouping does not happen
var groupByMonth2 =
from e in list
group e by new MonthYear { Month = e.chk.Month, Year = e.chk.Year } into g
select new MonthYearRates { MonthYear = g.Key, Rates = g.ToList()};
var monnthlyRatesDict2 = groupByMonth2.ToDictionary(t => t.MonthYear, t => t.Rates);
// Works. Dictionary has 329 entries
var groupByMonth3 =
from e in list
group e by new DateTime(e.chk.Year, e.chk.Month, 1) into g
select new MonthYearRates2 { MonthYear = g.Key, Rates = g.ToList() };
var monnthlyRatesDict3 = groupByMonth3.ToDictionary(t => t.MonthYear, t => t.Rates);
I tried to fix the problem by implementing IComparer and/or IComparable in the concrete type; to no avail
class MonthYear : IComparer
// class MonthYear : IComparable, IComparer
{
public MonthYear()
{
}
public MonthYear(int month, int year)
{
Month = month;
Year = year;
}
int IComparer.Compare(Object x, Object y)
{
MonthYear xo = (MonthYear)x;
MonthYear yo = (MonthYear)y;
if (yo.Year > xo.Year)
return 1;
else if (yo.Year < xo.Year)
return -1;
else
{
if (yo.Month > xo.Month)
return 1;
else if (yo.Month < xo.Month)
return -1;
else
return 0;
}
}
//int IComparable.CompareTo(object obj)
//{
// MonthYear o = (MonthYear)obj;
// if (Year > o.Year)
// return 1;
// else if (Year < o.Year)
// return -1;
// else
// {
// if (Month > o.Month)
// return 1;
// else if (Month < o.Month)
// return -1;
// else
// return 0;
// }
//}
public int Month;
public int Year;
}
I understand that Lookup might be a better fit that dictionary; I will lookup Lookup once I am done with anyonymous types.