Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I ease the pain of initializing dictionaries of Lists in C#?

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?

like image 230
Brann Avatar asked May 15 '09 09:05

Brann


1 Answers

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?

like image 104
tanascius Avatar answered Sep 28 '22 14:09

tanascius