Dictionary<DateTime, int> data1
Dictionary<DateTime, int> data2
未排序
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**
它可能是另一种方式。
bascailly我需要删除较小范围之外的条目 我怎么能用c#和linq做到这一点?
答案 0 :(得分:1)
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();
}
此处ShrinkDictionary
是:
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);
}
和InRange
是易于推广的方法:
public bool InRange(DateTime date, DateTime min, DateTime max) {
return (date >= min) && (date <= max);
}
答案 1 :(得分:0)
我假设您只需要从data2中删除条目(不要合并2个词典)
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);