我构建了一个基类,它保存了所有的主键,如:
public class PrimaryKey
{
[Key]
[Column(Order = 1)]
public DateTime Date { get; set; }
[Key]
[Column(Order = 2)]
public int ID1 { get; set; }
[Key]
[Column(Order = 3)]
public int ID2 { get; set; }
}
还有更多的类,从这个类派生出不同类型的数据。
然后,我想使用一种方法为这些派生类GroupBy主键创建列表。我现在所做的是:
private IEnumerable<IGrouping<PrimaryKey, T>> DataGroupByPrimaryKey<T>(IEnumerable<T> source) where T : PrimaryKey
{
return source.GroupBy(s => new PrimaryKey
{
Date = s.Date,
ID1 = s.ID1,
ID2 = s.ID2
});
}
但是它看起来不起作用,因为在程序通过这个方法之后,具有相同主键集的列表仍然保持未分组。
我做了这样的实验
source.GroupBy(s => new
{
s.Date,
s.ID1,
s.ID2
});
它确实使数据分组,但由于GroupBy类型是匿名的,因此不适合该方法。
我原来写的方法有什么问题吗?
已编辑的和添加的更多信息
很抱歉没有把我的问题说清楚。实际上,我现在所做的是将数据复制到不同的数据库中,并且每一行都应该根据这些键的集合是唯一的。(然后这个集合被称为主键)
在原始数据中,有具有相同主键集的行。因此,在GroupBy过程之后,我将使用相同的主键集对数据进行求和,并将其转换为字典。
sourceAfterGroupBy.Select(s => new DerivedClassWithData
{
Date = s.Key.Date,
ID1 = s.Key.ID1,
ID2 = s.Key.ID2,
Data1 = s.Sum(p => p.Data1),
Data2 = s.Sum(p => p.Data2)
});
dataSum.ToDictionary(s => s.PrimaryKeyTuple);
现在唯一的问题是,如果我在GroupBy函数中使用匿名类型,它肯定可以将我的数据按密钥集分组。但是如果我想使用PrimaryKey类型,在方法之后,它们仍然是未分组的,我只是想知道为什么会发生这种情况。
发布于 2016-04-25 04:46:22
让PrimaryKey实现IEquable接口并覆盖Object.GetHashCode方法。代码希望:
public class PrimaryKey : IEquable<PrimaryKey>
{
// other properties
bool Equals(PrimaryKey other)
{
return this.Date == other.Date && this.ID1 == other.ID1 && this.ID2 == other.ID2;
}
override int GetHashCode()
{
return this.Date.GetHashCode() ^ this.ID2.GetHashCode() ^ this.ID2.GetHashCode();
}
}
https://stackoverflow.com/questions/36832068
复制相似问题