Reputation: 45
I build a base class which keeps all the primary keys like:
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; }
}
and some more classes with different kind of data derived from this class.
Then I want to use one method to create lists for these derived class GroupBy primary keys. What I have done right now is:
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
});
}
but it looks like not working since after the program runs through this method, lists with the same set of primary keys still keep ungrouped.
I experimented with something like
source.GroupBy(s => new
{
s.Date,
s.ID1,
s.ID2
});
and it does make the data grouped, but since the GroupBy type is anonymous which is not suitable for the method.
Is there anything wrong in the original method I write?
[edited and more information added]
Sorry for not describing my question clearly. Actually what I am doing now is copying data into different databases, and each row should be unique by the set of these keys. (then the set is called primary key)
In the original data, there are rows with the same primary key set. So after the GroupBy process, I will sum the data with the same primary key set, and make it to dictionary.
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);
The only problem right now is, if I use anonymous type in the GroupBy function, it can surely group my data by the key set. But if I want to use the PrimaryKey type, after the method they are still ungrouped, and I just wonder why this happened.
Upvotes: 2
Views: 547
Reputation: 7036
Let PrimaryKey implement IEquable interface and override Object.GetHashCode method. Code would like:
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();
}
}
Upvotes: 2