Home > database >  Calling and writing a fuction containing ditionary keys and values
Calling and writing a fuction containing ditionary keys and values

Time:09-30

I'm currently making a small little game in C# and I have run into a small little problem that I can't seem to find the answer to, and I'm sorry if this question is too amateur, I really have tried searching a lot of stuff, maybe I'm using the wrong keywords etc.

Either way, I'm trying to make a function that writes out the current values of different keys in my dictionary, each while loop.

I've written a bit more about what I'm looking for in the comments of the code block - Thanks!

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices.ComTypes;
using System.Windows.Markup;

namespace MyApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> rutor =
                new Dictionary<string, string>();

            // Add some elements to the dictionary. There are no
            // duplicate keys, but some of the values are duplicates.
            rutor.Add("a1", "*");
            rutor.Add("a2", "*");
            rutor.Add("a3", "*");
            rutor.Add("a4", "*");
            rutor.Add("b1", "*");
            rutor.Add("b2", "*");
            rutor.Add("b3", "*");
            rutor.Add("b4", "*");
            rutor.Add("c1", "*");
            rutor.Add("c2", "*");
            rutor.Add("c3", "*");
            rutor.Add("c4", "*");
            rutor.Add("d1", "*");
            rutor.Add("d2", "*");
            rutor.Add("d3", "*");
            rutor.Add("d4", "*");

            //My very basic dictionary!
            //And what im now trying to do is creating a function that grabs these values 
            //and prints out the following by JUST calling the function, instead of writing    
            //these MANY lines! C#


            Console.Write($"{rutor["a1"]} ");
            Console.Write($"{rutor["a2"]} ");
            Console.Write($"{rutor["a3"]} ");
            Console.Write($"{rutor["a4"]}  a1  a2  a3  a4\n");
            Console.Write($"{rutor["b1"]} ");
            Console.Write($"{rutor["b2"]} ");
            Console.Write($"{rutor["b3"]} ");
            Console.Write($"{rutor["b4"]}  b1  b1  b3  b3\n");
            Console.Write($"{rutor["c1"]} ");
            Console.Write($"{rutor["c2"]} ");
            Console.Write($"{rutor["c3"]} ");
            Console.Write($"{rutor["c4"]}  c1  c2  c3  c4\n");
            Console.Write($"{rutor["d1"]} ");
            Console.Write($"{rutor["d2"]} ");
            Console.Write($"{rutor["d3"]} ");
            Console.Write($"{rutor["d4"]}  d1  d2  d3  d4\n");



            //Very messy code, but im just learning so hope you guys have a solutino to this                           
            // "inconvenience" 




CodePudding user response:

You can use a foreach for this learn more to iterate through your collection (dictionary).

foreach(var item in rutor)
{
    Console.Write($"{item.Value}");
}

CodePudding user response:

Assuming your keys are similar to what you've shown, one option would be to make groupings by the partial key and then iterate over those. This way, you know you're working with a keys separately from bs, cs, and ds.

Beware: this code makes some potentially dangerous assumptions. It's just an example of what you might do.

void PrintDict(Dictionary<string, string> dict)
{
    dict
        .GroupBy(pair => pair.Key.First())
        .ToList()
        .ForEach(group =>
        {
            var keys = new List<string>();
            foreach (var kvp in group.SkipLast(1))
            {
                keys.Add(kvp.Key);
                Console.WriteLine(kvp.Value);
            }

            var lastGroup = group.Last();
            keys.Add(lastGroup.Key);
            var last = $"{lastGroup.Value} {string.Join(' ', keys)}\n";
            Console.WriteLine(last);
        });
}

CodePudding user response:

Here you go.

public static void PrintDictionary(Dictionary<string, string> dic)
    {
    StringBuilder valueSb = new StringBuilder();
    StringBuilder keySb = new StringBuilder();
    int iterationCount = 0;
    foreach (var item in dic)
      {
      // value
      valueSb.Append(item.Value);
      valueSb.Append(" ");

      // key
      keySb.Append(item.Key);
      keySb.Append("  ");

      iterationCount  ;

      if (iterationCount == 4)
        {
        Console.Write(valueSb   " ");
        Console.Write(keySb.ToString());
        Console.WriteLine();
        iterationCount = 0;
        valueSb.Clear();
        keySb.Clear();
        }
      }
    }

You can call the function like this.

PrintDictionary(rutor);

CodePudding user response:

From your code sample, it seems like you want to list each [possibly duplicated] value in your dictionary, with each key related key.

If so, you can use System.Linq and do something like this:

using System;
using System.Collections.Generic;
using System.Linq;

namespace MyApplication
{
  public static class Program
  {
    public static void Main()
    {
      Dictionary<string, string> rutor = new Dictionary<string, string>
      {
        // Add some elements to the dictionary. There are no
        // duplicate keys, but some of the values are duplicates.
        {"a1", "v1"},
        {"a2", "v2"},
        {"a3", "v1"},
        {"a4", "v3"},
        {"b1", "v4"},
        {"b2", "v1"},
        {"b3", "v3"},
        {"b4", "v4"},
        {"c1", "v1"},
        {"c2", "v5"},
        {"c3", "v3"},
        {"c4", "v1"},
        {"d1", "v2"},
        {"d2", "*"},
        {"d3", "v1"},
        {"d4", "*"},
      };
      
      // A Dictionary<Tkey,Tvalue> is IEnumerable<KeyValuePair<Tkey,Tvalue> does the following:
      // - iterates over the key/value pairs in the dictionary,
      // - groups the keys by value, so now we have an enumerablie list of groups,
      //   each of which has a key and is itself an enumerable list of values.
      // - Each such group is then turned into a dictionary entry
      
      Dictionary<string,List<string>> keysByValue =
        rutor
        .GroupBy( tuple => tuple.Value , tuple => tuple.Key )
        .ToDictionary(
          g => g.Key,
          g => g.OrderBy( x => x ).ToList()
        );
      
      foreach (var kvp in keysByValue)
      {
        string value = kvp.Key ;
        string keys  = string.Join( " ",  kvp.Value );
        
        Console.WriteLine( "value: {0} keys: {1}", value , keys );
        
      }
      
    }
    
  }
  
}

Another (possibly simpler) approach is to roll your own.

using System;
using System.Collections.Generic;
using System.Linq;

namespace MyApplication
{
  public static class Program
  {
    public static void Main()
    {
      Dictionary<string, string> rutor = new Dictionary<string, string>
      {
        // Add some elements to the dictionary. There are no
        // duplicate keys, but some of the values are duplicates.
        {"a1", "v1"},
        {"a2", "v2"},
        {"a3", "v1"},
        {"a4", "v3"},
        {"b1", "v4"},
        {"b2", "v1"},
        {"b3", "v3"},
        {"b4", "v4"},
        {"c1", "v1"},
        {"c2", "v5"},
        {"c3", "v3"},
        {"c4", "v1"},
        {"d1", "v2"},
        {"d2", "*"},
        {"d3", "v1"},
        {"d4", "*"},
      };
        
      Dictionary<string,List<string>> keysByValue = new Dictionary<string,List<string>>();
      foreach (var kvp in rutor)
      {
          List<string> values;
          bool exists = keysByValue.TryGetValue( kvp.Value, out values );
          if ( !exists )
          {
              values = new List<string>();
              keysByValue[ kvp.Value ] = values;
          }
          values.Add( kvp.Key );
      }
     
      foreach (string value in keysByValue.Keys.OrderBy( s => s ) )
      {
        string keys = string.Join( " ",  keysByValue[value] );
        Console.WriteLine( "value: {0} keys: {1}", value , keys );
      }
      
    }
    
  }
  
}
  • Related