【发布时间】:2017-03-26 09:56:23
【问题描述】:
我正在尝试使用 Linq 将列表转换为字典。我已经能够使用匿名类型作为键获得正确的结果,但不能使用具体类型。请参阅下面的代码:
// 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);
我尝试通过在具体类型中实现 IComparer 和/或 IComparable 来解决问题;无济于事
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;
}
我了解 Lookup 可能更适合该词典;完成任何匿名类型后,我将查找 Lookup。
【问题讨论】:
-
匿名类型使用结构相等,通过反射检查类型的所有属性,具体类默认使用对象/引用相等。创建一个实现
IEqualityComparer<MonthYear>类型的自定义类。也就是说,不是 IComparer 而是作为一个单独的类。即class MonthYearEqualityComparer : IEqualityComparer<MonthYear>{...}并将其作为最后一个参数传递给ToDictionary方法 -
或者,如果您可以将 MonthYear 设置为不可变的
struct,则无需您进行任何工作(同样,默认情况下使用反射完成),您将获得结构平等,尽管这可能不是一个可行的选择
标签: c# linq linq-to-objects