Equalize data dictionary
Dictionary<DateTime, int> data1
Dictionary<DateTime, int> data2
not sorted
if the dates in data1 is from **1/1/2000 - 1开发者_如何学运维/1/2009** and the dates in data2 is from **1/1/2001 - 1/1/2007** then both Dictionaries<> should have the date ranging from **1/1/2001 - 1/1/2007**
it could be the other way around.
bascailly i need to remove the entries that are outside of the smaller range how can i do this using c# and linq?
DateTime min1 = data1.Keys.Min();
DateTime min2 = data2.Keys.Min();
DateTime max1 = data1.Keys.Max();
DateTime max2 = data1.Keys.Max();
if(min1 < min2 && max1 > max2) {
data1 = ShrinkDictionary(data1, min2, max2);
}
else if(min2 < min1 && max2 > max1) {
data2 = ShrinkDictionary(data2, min1, max1);
}
else {
// this should never happen
throw new Exception();
}
Here ShrinkDictionary
is:
public Dictionary<DateTime, int> ShrinkDictionary(
Dictionary<DateTime, int> dict, DateTime min, DateTime max) {
return dict.Where(kvp => InRange(kvp.Key, min, max))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
}
and InRange
is the easily-generalizable method:
public bool InRange(DateTime date, DateTime min, DateTime max) {
return (date >= min) && (date <= max);
}
I assume you just need to remove entries from data2 (not to merge 2 dictionaries)
var min = data1.Keys.Min();
var max = data1.Keys.Max();
data2 = data2
.Where(pair => pair.Key >= min && pair.Key < max)
.ToDictionary(pair => pair.Key, pair => pair.Value);
精彩评论