2009-11-06 2 views
0
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을 사용하여이 작업을 수행 할 수 있습니까?

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 쉽게-일반화 방법은 다음과 같습니다

+0

이 예에서 예. 하지만 둘 중 하나 일 수 있습니다. – newmem

+0

'entry.Key '가 2001 년 1 월 1 일보다 크고'entry.Key'가 2007 년 1 월 1 일보다 작은'entry1'를'data1'에서 제거하고 싶다고 올바르게 이해하고 있습니까? 이것이 사실 인 것처럼 보이지만 그렇다면'data2'의 요점을 보지 못합니까? – jason

+0

여기서 entry.Key가 2001 년 1 월 1 일보다 작고 entry.Key가 2007 년 1 월 1 일보다 큰 경우 data1에서 제거하십시오. data2는 동일하게 유지됩니다. – newmem

답변

0

난 그냥

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); 
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가 (2 개 사전을 병합하지 않음) 데이터 2에서 항목을 제거 할 필요가 가정 :

public bool InRange(DateTime date, DateTime min, DateTime max) { 
    return (date >= min) && (date <= max); 
} 
관련 문제