Iteratate Dictionay of List

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • =?Utf-8?B?THVpZ2k=?=

    Iteratate Dictionay of List

    Hi all,
    I have a dictionary like this:

    Dictionary<List <string>, List<string>>

    How can I iterate in it?

    Thanks very much.
    --
    Luigi

  • Marc Gravell

    #2
    Re: Iteratate Dictionay of List

    Well, what do you want to iterate? Each key (a List<string>) could have
    multiple valies - do you just want the values?

    With C# 3.0 / .NET 3.5, SelectMany is an option, but I guess (last post)
    that this isn't an option. So you'll just need a few nested foreach loops.

    Marc

    Comment

    • =?Utf-8?B?THVpZ2k=?=

      #3
      Re: Iteratate Dictionay of List

      "Marc Gravell" wrote:
      Well, what do you want to iterate? Each key (a List<string>) could have
      multiple valies - do you just want the values?
      >
      With C# 3.0 / .NET 3.5, SelectMany is an option, but I guess (last post)
      that this isn't an option. So you'll just need a few nested foreach loops.
      Yes, I'm using C# 2.0, so many useful options are prohibited for me.
      What I'd like is to obtain the collection of strings for every string of the
      first List in my dictionary.

      Luigi

      Comment

      • Marc Gravell

        #4
        Re: Iteratate Dictionay of List

        Yes, I'm using C# 2.0, so many useful options are prohibited for me.
        What I'd like is to obtain the collection of strings for every string of the
        first List in my dictionary.
        Can you show that with a simple example?

        i.e.
        "if the data was as bloe, then I want {your bit here}

        item 1: key (list) "a", "b"
        value (list) "c", "d", "e"
        item 2: key (list) "f"
        value (list) "g", "h"

        Marc

        Comment

        • =?Utf-8?B?THVpZ2k=?=

          #5
          Re: Iteratate Dictionay of List

          "Marc Gravell" wrote:
          Yes, I'm using C# 2.0, so many useful options are prohibited for me.
          What I'd like is to obtain the collection of strings for every string of the
          first List in my dictionary.
          >
          Can you show that with a simple example?
          >
          i.e.
          "if the data was as bloe, then I want {your bit here}
          >
          item 1: key (list) "a", "b"
          value (list) "c", "d", "e"
          item 2: key (list) "f"
          value (list) "g", "h"
          I can't use the ContainsKey method of my Dictionary passing a List<string>
          that is contained.

          L

          Comment

          • Marc Gravell

            #6
            Re: Iteratate Dictionay of List

            See below; I expect the problem is that you are passing a *different*
            list that has the same data. By default, the lists are compared for
            object (reference) equality. It is possible to override this behavior by
            performing a custom comparison (so that two lists with the same contents
            are treated as equal). Let me know if you need this.

            Marc

            class Program
            {
            static void Main()
            {
            Dictionary<List <string>, List<string>loo kup = new
            Dictionary<List <string>, List<string>>() ;
            lookup.Add(Wrap ("a", "b"), Wrap("c", "d", "e"));
            lookup.Add(Wrap ("f"), Wrap("g", "h"));

            List<stringfirs tKey = null;
            foreach (KeyValuePair<L ist<string>, List<string>pai r in lookup)
            {
            if (firstKey == null) firstKey = pair.Key;
            Write(pair.Key, "Key");
            Write(pair.Valu e, "Value");
            }

            if (lookup.Contain sKey(firstKey))
            {
            List<stringvalu e = lookup[firstKey];
            Write(value, "Value By Key");
            }
            }
            static void Write<T>(List<T list, string caption)
            {
            Console.WriteLi ne(caption);
            foreach (T t in list)
            {
            Console.WriteLi ne("\t{0}", t);
            }
            }
            static List<TWrap<T>(p arams T[] args)
            {
            return new List<T>(args);
            }
            }

            Comment

            • Marc Gravell

              #7
              Re: Iteratate Dictionay of List

              To treat different lists (with the same contents) as equal, you need to
              provide a custom IEqualityCompar er<Tto the dictionary's constructor.

              The following should suffice, used with:

              ... lookup = new Dictionary<List <string>,
              List<string>>(L istComparer<str ing>.Default);

              Marc

              class ListComparer<T: IEqualityCompar er<List<T>>
              {
              private readonly IEqualityCompar er<TitemCompare r;
              public static readonly ListComparer<TD efault = new ListComparer<T> ();
              public ListComparer() : this(null) { }
              public ListComparer(IE qualityComparer <TitemCompare r)
              {
              this.itemCompar er = itemComparer ?? EqualityCompare r<T>.Default;
              }

              bool IEqualityCompar er<List<T>>.Equ als(List<Tx, List<Ty)
              {
              if (ReferenceEqual s(x, y)) return true;
              int len;
              if (x == null || y == null || (len = x.Count) != y.Count)
              return false;
              for (int i = 0; i < len; i++)
              {
              if (!itemComparer. Equals(x[i], y[i])) return false;
              }
              return true;
              }

              int IEqualityCompar er<List<T>>.Get HashCode(List<T list)
              {
              if (list == null) return 0;
              int agg = 3;
              foreach (T item in list)
              {
              agg *= 13;
              agg += 7 * itemComparer.Ge tHashCode(item) ;
              }
              return agg;
              }
              }

              Comment

              • Peter Morris

                #8
                Re: Iteratate Dictionay of List

                Are you sure you don't want something like

                Dictionary<stri ng, Dictionary<stri ng, string>>

                Your data structure seems quite useless to me. What are you intending to
                store within it, and how do you intend to use that data?


                --
                Pete
                ====



                Comment

                • =?Utf-8?B?THVpZ2k=?=

                  #9
                  Re: Iteratate Dictionay of List

                  "Marc Gravell" wrote:
                  See below; I expect the problem is that you are passing a *different*
                  list that has the same data. By default, the lists are compared for
                  object (reference) equality. It is possible to override this behavior by
                  performing a custom comparison (so that two lists with the same contents
                  are treated as equal). Let me know if you need this.
                  >
                  Marc
                  >
                  class Program
                  {
                  static void Main()
                  {
                  Dictionary<List <string>, List<string>loo kup = new
                  Dictionary<List <string>, List<string>>() ;
                  lookup.Add(Wrap ("a", "b"), Wrap("c", "d", "e"));
                  lookup.Add(Wrap ("f"), Wrap("g", "h"));
                  >
                  List<stringfirs tKey = null;
                  foreach (KeyValuePair<L ist<string>, List<string>pai r in lookup)
                  {
                  if (firstKey == null) firstKey = pair.Key;
                  Write(pair.Key, "Key");
                  Write(pair.Valu e, "Value");
                  }
                  >
                  if (lookup.Contain sKey(firstKey))
                  {
                  List<stringvalu e = lookup[firstKey];
                  Write(value, "Value By Key");
                  }
                  }
                  static void Write<T>(List<T list, string caption)
                  {
                  Console.WriteLi ne(caption);
                  foreach (T t in list)
                  {
                  Console.WriteLi ne("\t{0}", t);
                  }
                  }
                  static List<TWrap<T>(p arams T[] args)
                  {
                  return new List<T>(args);
                  }
                  }
                  >
                  Thank you Marc, very interesting.
                  Now I'm trying to using this code in my project.

                  Luigi

                  Comment

                  • =?Utf-8?B?THVpZ2k=?=

                    #10
                    Re: Iteratate Dictionay of List

                    In the first string I have a name of check.
                    In the inner dictionary I have a list of objects that have to match together.
                    For example

                    "check1" is the key of the outer dictionary.

                    then I have "value1", "value2" is the key of the inner dic, and
                    "innervalue 1", "innervalue 2", "innervalue 3" are the values.

                    Luigi

                    Comment

                    • =?Utf-8?B?THVpZ2k=?=

                      #11
                      Re: Iteratate Dictionay of List

                      Another question Marc.
                      How can I write a methods that returns me the composition of the inner
                      dictionary?
                      For example, for the first KeyValuePair of the first List<stringI'd like
                      to obtain the List<stringvalu e of the inner dictionary.

                      Luigi

                      Comment

                      • Peter Morris

                        #12
                        Re: Iteratate Dictionay of List

                        Looks more like you want this...

                        Dictionary<stri ng, Dictionary<stri ng, List<string>>>


                        Take a look at this....


                        using System;
                        using System.Collecti ons.Generic;
                        using System.Text;

                        namespace ConsoleApplicat ion7
                        {
                        class Program
                        {
                        static void Main(string[] args)
                        {
                        Dictionary<stri ng, Dictionary<stri ng, List<string>>ch ecks = new
                        Dictionary<stri ng, Dictionary<stri ng, List<string>>>( );

                        for (int checkNumber = 0; checkNumber < 10; checkNumber++)
                        {
                        checks.Add("Che ck" + checkNumber.ToS tring(), CreateCheck());
                        }

                        foreach (var currentCheck in checks)
                        {
                        Console.WriteLi ne("CurrentChec k: " + currentCheck.Ke y);
                        foreach (var currentValue in currentCheck.Va lue)
                        {
                        Console.WriteLi ne(" Current value: " + currentValue.Ke y);
                        foreach (var currentInnerVal ue in currentValue.Va lue)
                        Console.WriteLi ne(" Current inner value: " + currentInnerVal ue);
                        Console.ReadLin e();
                        }
                        }

                        }

                        private static Dictionary<stri ng, List<string>Cre ateCheck()
                        {
                        var result = new Dictionary<stri ng, List<string>>() ;
                        for (int valueNumber = 0; valueNumber < 10; valueNumber++)
                        {
                        result.Add("Val ue" + valueNumber.ToS tring(), CreateInnerValu es());
                        }
                        return result;
                        }

                        private static List<stringCrea teInnerValues()
                        {
                        return new List<string>(ne w string[] { "One", "Two", "Three" });
                        }

                        }
                        }

                        Comment

                        • =?Utf-8?B?THVpZ2k=?=

                          #13
                          Re: Iteratate Dictionay of List

                          Having this code:

                          Dictionary<stri ng, Dictionary<stri ng[], string[]>outerCheck =
                          new Dictionary<stri ng, Dictionary<stri ng[], string[]>>();

                          Dictionary<stri ng[], string[]innerCheck = new Dictionary<stri ng[],
                          string[]>();
                          string[] vociReference1 = {"Tava|a", "Tavb|b"};
                          string[] vociBalancing1 = {"Tavm|m", "Tavn|n"};

                          innerCheck.Add( vociReference1, vociBalancing1) ;

                          outerCheck.Add( "Check1", innerCheck);

                          Dictionary<stri ng[], string[]innerCheckTest = new Dictionary<stri ng[],
                          string[]>();
                          innerCheckTest = outerCheck["Check1"];

                          Dictionary<stri ng[], string[]>.KeyCollecti on keys = innerCheckTest. Keys;

                          string[] myKeys;

                          I can't populate this array.
                          What's wrong?

                          L


                          Comment

                          Working...