tags:

views:

53

answers:

2
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?

A: 

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);
Boris Lipschitz
+1  A: 
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);
}
Jason
what if the range of data1 and data2 are unknown, how do i find which one is the smaller one?
newmem
@newmem: Are you always assuming that the range of one will fit in the range of the other?
Jason
@jason yes that's right
newmem
@newmem: See my edit.
Jason