How can I alleviate the pain of initializing list dictionaries in C #?

I often use this structure:

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 your own DictionaryOfList class that would automatically handle such things?

Is there any other way to lazily initialize these lists?

+5
source share
6 answers

You can write an extension method - GetValueOrCreateDefault () or something like this:

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 all initialization?

+7
source

... .NET 3.5, ILookup<TKey,TValue>. (Lookup<TKey,TValue>) , EditableLookup<TKey,TValue> MiscUtil. - i.e.

var data = new EditableLookup<string, int>();
data.Add("abc",123);
data.Add("def",456);
data.Add("abc",789);

foreach(int i in data["abc"]) {
    Console.WriteLine(i); // 123 & 789
}

, :

public static void Add<TKey, TList, TValue>(
    this IDictionary<TKey, TList> lookup,
    TKey key, TValue value)
    where TList : class, ICollection<TValue>, new()
{
    TList list;
    if (!lookup.TryGetValue(key, out list))
    {
        lookup.Add(key, list = new TList());
    }
    list.Add(value);
}

static void Main() {
    var data = new Dictionary<string, List<string>>();
    data.Add("abc", "def");
}
+4

, :

class DictionaryOfList : Dictionary<string, List<string>> {} 
  • . . Tanascius .
+2

System.Data.DataSetExtensions, Linq:

var dictOfLst = ds.Tables[0].Rows.
    //group by the key field
    GroupBy( dr => dr.Field<string>("key") ).
    ToDictionary(
        grp => grp.Key,
        //convert the collection of rows into values
        grp => grp.Select( dr => dr.Field<string>("value") ).ToList() );

, , :

public static Dictionary<TKey, List<TValue>> ToGroupedDictionary<TKey, List<TValue>>(
    this DataTable input, 
    Func<TKey, DataRow> keyConverter, 
    Func<TValue, DataRow> valueConverter )
{
    return input.Rows.
        //group by the key field
        GroupBy( keyConverter ).
        ToDictionary(
            grp => grp.Key,
            //convert the collection of rows into values
            grp => grp.Select( valueConverter ).ToList() );
}

//now you have a simpler syntax
var dictOfLst = ds.Tables[0].ToGroupedDictionary(
    dr => dr.Field<string>("key"),
    dr => dr.Field<string>("value") );
+1

using.

This is not an immediate answer, but may be useful in any case. Using a nickname for a generic collection type can make your code easier on the eyes.

using StoreBox = System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>>; 
using ListOfStrings = System.Collections.Generic.List<string>; 
class Program
{
    static void Main(string[] args)
    {
      var b = new StoreBox ();
      b.Add("Red", new ListOfStrings {"Rosso", "red" });
      b.Add("Green", new ListOfStrings {"Verde", "green" });
    }
}

Thanks to SO for this hint.

0
source

Why not just simplify a bit:

foreach (DataRow dr in ds.Tables[0].Rows)
{
   string key = dr["Key"].ToString();
   if (!Foo.ContainsKey(key)) Foo.Add(key, new List<string>());
   Foo[key].Add(dr["Value"].ToString());
}
0
source