Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move object between dictionaries?

I have simple task where I need to check objects in one dictionary and if certain criteria met move to another. What I am asking if there is some good pattern where I can use language feature to achieve that. The straight approach is simple - use temporaty collection, first step determine canditates, second step do actual move. It is ok but it is not cool.

Current code

class Order
{
  public int ID;
  public bool IsReady;
}

Dictionary<int, Order> ActiveDictionary;
Dictionary<int, Order> ProcessedDictionary;

public Update()
{    
 // temporary list, uncool
 List<Order> processed = new List<Order>();


 // fist step
 foreach(Order ord in ActiveDictionary)
 {
  if(ord.IsReady)
  {
    processed.Add(ord);
  }
 }

 // ok now lets move
 foreach(Order ord in processed)
 {
  ActiveDictionary.Remove(ord.ID);
  ProcessedDictionary.Add(ord.ID, ord);
 }
}
like image 794
Captain Comic Avatar asked Dec 01 '10 12:12

Captain Comic


1 Answers

There is nothing really wrong with the code you have.

As an exercise in alternatives, you could do something like...

ProcessedDictionary = ProcessedDictionary
    .Concat(
        ActiveDictionary.Where(kvp => kvp.Value.Ready)
    )
    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

ActiveDictionary = ActiveDictionary.Where(kvp => !kvp.Value.Ready)
    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
like image 154
Rex M Avatar answered Sep 18 '22 12:09

Rex M