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);
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With