I happen to use this kind of structure quite a lot:
Dictionary<string, List<string>> Foo = new Dictionary<string, List<string>>();
Which leads to this kind of code :
foreach (DataRow dr in ds.Tables[0].Rows)
{
    List<string> bar;
    if (!Foo.TryGetValue(dr["Key"].ToString(), out desks))
    {
        bar= new List<string>();
        Foo.Add(dr["Key"].ToString(), bar);
    }
    bar.Add(dr["Value"].ToString());
}
Do you think it's worth writing a custom DictionaryOfList class which would handle this kind of things automatically?
Is there another way to lazily initialize those Lists?
You can write an extension method - GetValueOrCreateDefault() or something like that:
foreach (DataRow dr in ds.Tables[0].Rows)
{
    Foo.GetValueOrCreateDefault( dr["Key"] ).Add( dr["Value"].ToString() )
}
Maybe you can even write an extension method for the whole initialisation?
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