我构建了一个基类,它保留所有主键,例如:
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 类型,在该方法之后它们仍然未分组,我只是想知道为什么会发生这种情况。
最佳答案
让 PrimaryKey 实现 IEquable接口(interface)和覆盖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();
}
}
关于C# LINQ 按基类分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36832068/