2012-02-01 2 views
0

한 사전에서 요소를 이동하면 내가 이동해야 해이다 이 Car부터 KeyValuePair까지 새해의 연도는 KeyValuePair입니다.내가 몇 쌍</p> <pre><code>Dictionary<DateTime, ObservableCollection<Car>> </code></pre> <p>와 나는 <code>Car</code>의 생산 연도를 변경하고있어, 및 <code>Key</code> (<code>DateTime</code>) 때문에와 사전을 가지고 다른

1.1.1997 {Car1,Car2} 
1.1.1998 {Car3} 

내가

1.1.1997 {Car1} 
1.1.1998 {Car3,Car2} 

것을 달성 할 수있는 가장 쉬운 방법은 무엇입니까이 필요

Car2.Production = Convert.ToDateTime("1.1.1998"); 

의 :

그래서 예를 들어, 저는 두 쌍을했다?

+2

알아보기 쉬운 방법이 있는지 모르겠습니다. 'Dictionary'에서'Key '로 제작 년도의'DateTime '을 다시 생각해 볼 수 있습니다. 이것이 데이터베이스라면 꽤 불쾌한 기능 의존성을 도입했을 것입니다. – Yuck

+0

코드 냄새가 있음을 알고 있지만 리팩터링 할 시간이별로 없습니다. 그 코드로 작업해야합니다. – user278618

+0

'생산'값을 수정하기 위해 개별 '자동차'를 꺼내는 코드 영역의'Dictionary >'에 액세스 할 수 있습니까? – Yuck

답변

2

이 데이터 대신 그룹화 된보기를 사용할 수도 있지만 여기에 설명 된대로 문제를 해결하는 코드 솔루션이 있습니다. 둘 이상의 속성에 대해이 작업을 수행하려는 경우 DependencyObject에서 Car를 상속 받거나 각각에 대한 이벤트를 만드는 대신 INotifyPropertyChanged에서 Car를 구현하는 것이 좋습니다.

// The car class itself 
public class Car 
{ 
    // This event is raised when the production property changes 
    public event EventHandler<PropertyValueChange<DateTime>> ProductionChanged; 
    DateTime _production; // private data 
    public DateTime Production 
    { 
     get { return _production; } 
     set 
     { 
      if (value == _production) return; // don't raise the event if it didn't change 
      var eventArgs = new PropertyValueChange<DateTime>(_production, value); 
      _production = value; 
      // If anyone is "listening," raise the event 
      if (ProductionChanged != null) 
       ProductionChanged(this, eventArgs); 
     } 
    } 
} 
// Class that contains the dictionary of production to car lists 
class Foo 
{ 
    Dictionary<DateTime, ObservableCollection<Car>> ProductionToCars = new Dictionary<DateTime, ObservableCollection<Car>>(); 

    public void Add(Car c) 
    { 
     _Add(c); 
     // We want to be notified when the car's production changes 
     c.ProductionChanged += this.OnCarProductionChanged; 
    } 
    // This is called when a car's value changes, and moves the car 
    void OnCarProductionChanged(object sender, PropertyValueChange<DateTime> e) 
    { 
     Car c = sender as Car; 
     if (c == null) return; 
     ProductionToCars[e.OldValue].Remove(c); 
     _Add(c); 
    } 
    // this actually places the car in the (currently correct) group 
    private void _Add(Car c) 
    { 
     ObservableCollection<Car> collection; 
     // Find the collection for this car's year 
     if (!ProductionToCars.TryGetValue(c.Production, out collection)) 
     { 
      // if we couldn't find it, create it 
      collection = new ObservableCollection<Car>(); 
      ProductionToCars.Add(c.Production, collection); 
     } 
     // Now place him in the correct collection 
     collection.Add(c); 
    } 

} 
// This class encapsulates the information we'll pass when the property value changes 
public class PropertyValueChange<T> : EventArgs 
{ 
    public T OldValue; 
    public T NewValue; 
    public PropertyValueChange(T oldValue, T newValue) 
    { 
     OldValue = oldValue; 
     NewValue = newValue; 
    } 
} 
1

이 작동합니다 (하지 짧은 코드 가능하지만, 간단한 이해하기) :

private static void EnsureValuesAreCoherent(Dictionary<DateTime, ObservableCollection<Car>> param) 
{ 
    List<Car> toMove = new List<Car>(); 
    foreach (KeyValuePair<DateTime, ObservableCollection<Car>> pair in param) 
    { 
     List<Car> toRemove = new List<Car>(); 
     foreach (Car car in pair.Value) 
     { 
      if (car.Production != pair.Key) 
      { 
       toRemove.Add(car); 
      } 
     } 

     foreach (Car car in toRemove) 
     { 
      pair.Value.Remove(car); 
      toMove.Add(car); 
     } 
    } 

    foreach (Car car in toMove) 
    { 
     ObservableCollection<Car> currentCollection; 
     if (param.TryGetValue(car.Production, out currentCollection)) 
     { 
      currentCollection.Add(car); 
     } 
    } 
} 

을하지만, IMO는 이러한 사전의 키 사이의 종속성과 사전의 회원을 가지고 나쁜 생각 값.

1

이 경우 사전이 있어야합니까? requierment는 특정 생산 날짜의 모든 자동차에서 작동 할 수 있기를 원한다면 Linq를 사용할 수 있습니까? 특정 연도에 모든 차량에 액세스 할 수 있습니다이 방법을 사용

ObservableCollection<Car> cars = new ObservableCollection<Car>(); 
var car1 = new Car() { Model = "Ford", ProductionDate = new DateTime(1997, 01, 01)}); 
var car2 = new Car() { Model = "Chevy", ProductionDate = new DateTime(1997, 01, 01)}); 
var car3 = new Car() { Model = "Ford", ProductionDate = new DateTime(2002, 01, 01)}); 
cars.Add(car1); 
cars.Add(car2); 
cars.Add(car3); 

var carsIn1997 = cars.Where(x => x.ProductionDate.Year == 1997); 
var carsThatAreFords = cars.Where(x => x.Model == "Ford"); 
var groupedCars = cars.GroupBy(x => x.ProductionDate); 

, 모델 등 ... 등 주변 이동 참조에 대한 걱정없이, 데이터를 조작 ... 일반 GROUPBY 자습서

, here

관련 문제