none
dictionary key value issue RRS feed

  • Question

  • ok so i have made a program that i am genrating a a dict to key value pairs and in this key value pairs they are enclosed in "" 

    so i used the escape \ but when i adds the key value pair it adds it in like this

    this is the code i have currently 

    smgwep.Add("\"activate_mode\"", "\"hold\"");
                smgwep.Add("\"activate_with_primed_delay\"", "\"0\"");
                smgwep.Add("\"activatesSlam\"", "\"0\"");
                smgwep.Add("\"activatesSlamAsMelee\"", "\"0\"");
                smgwep.Add("\"activatesSlamAsPowerMelee\"", "\"0\"");
                smgwep.Add("\"activatesSlamAsPowerMeleeLeft\"", "\"0\"");
                smgwep.Add("\"acv_acog\"", "\"\"");
                smgwep.Add("\"acv_damage\"", "\"\"");
                smgwep.Add("\"acv_dualclip\"", "\"\"");
                smgwep.Add("\"acv_dualoptic\"", "\"\"");
                smgwep.Add("\"acv_dw\"", "\"\"");
                smgwep.Add("\"acv_dynzoom\"", "\"\"");
                smgwep.Add("\"acv_extbarrel\"", "\"\"");
                smgwep.Add("\"acv_extclip\"", "\"\"");
                smgwep.Add("\"acv_fastads\"", "\"\"");
                smgwep.Add("\"acv_fastreload\"", "\"\"");
                smgwep.Add("\"acv_fmj\"", "\"\"");
                smgwep.Add("\"acv_gl\"", "\"\"");
                smgwep.Add("\"acv_gmod0\"", "\"\"");
                smgwep.Add("\"acv_gmod1\"", "\"\"");
                smgwep.Add("\"acv_gmod2\"", "\"\"");
                smgwep.Add("\"acv_gmod3\"", "\"\"");
                smgwep.Add("\"acv_gmod4\"", "\"\"");
                smgwep.Add("\"acv_gmod5\"", "\"\"");
                smgwep.Add("\"acv_gmod6\"", "\"\"");
                smgwep.Add("\"acv_gmod7\"", "\"\"");
                smgwep.Add("\"acv_grip\"", "\"\"");
                smgwep.Add("\"acv_holo\"", "\"\"");
                smgwep.Add("\"acv_ir\"", "\"\"");
                smgwep.Add("\"acv_is\"", "\"\"");
                smgwep.Add("\"acv_mk\"", "\"\"");
                smgwep.Add("\"acv_mms\"", "\"\"");
                smgwep.Add("\"acv_none\"", "\"\"");

    it saves out the the file ok puts in the quotes and format and all but the issue is the key names have the 

    "\"activate_mode\"" "\"hold\""

    and i wanted to know is there a way to remove the "\" form the key name so i can search smgwep["activate_mode"]

    and on the save out it still save it within the quotes 

    the save out function 

            public void saveout()
            {
                smgwep_class();
                using (StreamWriter writer = new StreamWriter(@"C:\Users\elfenliedtopfan5\Desktop\pdw.gdt"))
                {
                    writer.Write("{" + Environment.NewLine);
                    writer.WriteLine(    smgwep["displayName"] + "(\"bulletweapon.gdf\")"); //    "\"pdw57\"(\"bulletweapon.gdf\")"
                    writer.WriteLine(	"}"+ Environment.NewLine);
    
                   foreach (var entry in smgwep)
                   writer.WriteLine("		{0} {1}", entry.Key, entry.Value);
                }
            }

    thats how i want it to be but currently it tells me displayName does not exsist in dict witch is because it has all the "/ ect in frount of it 

    any help would be much appeicated 

    elfenliedtopfan5 


    Monday, July 8, 2019 12:10 PM

Answers

  • It looks like, based upon your screenshot, that you took the method and tried to put it into the class you were already defining (given the field declarations after it). This is an extension method and extension methods must be in static classes. In my posted code I had created a `StringExtensions` static class. Put that entire class into your project, don't try to extract the method out of it.

    Michael Taylor http://www.michaeltaylorp3.net

    Monday, July 8, 2019 4:31 PM
    Moderator

All replies

  • Why are you explicitly putting double quotes in the string literal? Put them in only when, if you need them. 

    Also, your format looks partially like JSON but it isn't formatted properly. If you're trying to write out a JSON file then use a JSON serializer instead of doing it manually. 

    Here's a simple solution using an extension method. You could simplify the save logic if you wanted to use LINQ. Probably down to 2 or 3 lines. Additionally it looks to me like the dictionary is more of a type so I'd recommend moving the dictionary and save/load logic into a type so it is self contained.

    class Program
    {
        static void Main ( string[] args )
        {
            var smgwep = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
    
            smgwep.Add("activate_mode", "hold");
            smgwep.Add("activate_with_primed_delay", "0");
            smgwep.Add("activatesSlam", "0");
    
            var activateMode = smgwep["activate_mode"];
    
            SaveFile(smgwep, @"C:\temp\test.gdt");
        }
    
        static void SaveFile ( Dictionary<string, string> values, string filename )
        {
            using (var writer = new StreamWriter(filename))
            {
                writer.WriteLine("{");
                writer.WriteLine($"{values["displayName"].WrapInDoubleQuotes()}{"bulletweapon.gdf".WrapInDoubleQuotes()}");
                writer.WriteLine("}");
    
                foreach (var value in values)
                    writer.WriteLine($"\t\t{value.Key.WrapInDoubleQuotes()} {value.Value.WrapInDoubleQuotes()}");
            };
        }
    }
    
    static class StringExtensions
    {
        //Helper method but you could do this inline as well
        public static string WrapInDoubleQuotes ( this string source )
        {
            if (source == null)
                return null;
    
            if (!source.StartsWith("\""))
                if (!source.EndsWith("\""))
                    return "\"" + source + "\"";
                else
                    return "\"" + source;
            else if (!source.EndsWith("\""))
                return source + "\"";
    
            return source;
        }
    }


    Michael Taylor http://www.michaeltaylorp3.net

    Monday, July 8, 2019 1:53 PM
    Moderator
  • Why are you explicitly putting double quotes in the string literal? Put them in only when, if you need them. 

    Also, your format looks partially like JSON but it isn't formatted properly. If you're trying to write out a JSON file then use a JSON serializer instead of doing it manually. 

    Here's a simple solution using an extension method. You could simplify the save logic if you wanted to use LINQ. Probably down to 2 or 3 lines. Additionally it looks to me like the dictionary is more of a type so I'd recommend moving the dictionary and save/load logic into a type so it is self contained.

    class Program
    {
        static void Main ( string[] args )
        {
            var smgwep = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
    
            smgwep.Add("activate_mode", "hold");
            smgwep.Add("activate_with_primed_delay", "0");
            smgwep.Add("activatesSlam", "0");
    
            var activateMode = smgwep["activate_mode"];
    
            SaveFile(smgwep, @"C:\temp\test.gdt");
        }
    
        static void SaveFile ( Dictionary<string, string> values, string filename )
        {
            using (var writer = new StreamWriter(filename))
            {
                writer.WriteLine("{");
                writer.WriteLine($"{values["displayName"].WrapInDoubleQuotes()}{"bulletweapon.gdf".WrapInDoubleQuotes()}");
                writer.WriteLine("}");
    
                foreach (var value in values)
                    writer.WriteLine($"\t\t{value.Key.WrapInDoubleQuotes()} {value.Value.WrapInDoubleQuotes()}");
            };
        }
    }
    
    static class StringExtensions
    {
        //Helper method but you could do this inline as well
        public static string WrapInDoubleQuotes ( this string source )
        {
            if (source == null)
                return null;
    
            if (!source.StartsWith("\""))
                if (!source.EndsWith("\""))
                    return "\"" + source + "\"";
                else
                    return "\"" + source;
            else if (!source.EndsWith("\""))
                return source + "\"";
    
            return source;
        }
    }


    Michael Taylor http://www.michaeltaylorp3.net

    umm having a issue with the wrappedinquotes() class 

    i tried all i know i had issue like this before and removing the this form it worked but this is giving me a problem and not sure how to resolve it 

    sorry to be a pain elfenliedtopfan5

    Monday, July 8, 2019 3:25 PM
  • Why are you explicitly putting double quotes in the string literal? Put them in only when, if you need them. 

    Also, your format looks partially like JSON but it isn't formatted properly. If you're trying to write out a JSON file then use a JSON serializer instead of doing it manually. 

    Here's a simple solution using an extension method. You could simplify the save logic if you wanted to use LINQ. Probably down to 2 or 3 lines. Additionally it looks to me like the dictionary is more of a type so I'd recommend moving the dictionary and save/load logic into a type so it is self contained.

    class Program
    {
        static void Main ( string[] args )
        {
            var smgwep = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
    
            smgwep.Add("activate_mode", "hold");
            smgwep.Add("activate_with_primed_delay", "0");
            smgwep.Add("activatesSlam", "0");
    
            var activateMode = smgwep["activate_mode"];
    
            SaveFile(smgwep, @"C:\temp\test.gdt");
        }
    
        static void SaveFile ( Dictionary<string, string> values, string filename )
        {
            using (var writer = new StreamWriter(filename))
            {
                writer.WriteLine("{");
                writer.WriteLine($"{values["displayName"].WrapInDoubleQuotes()}{"bulletweapon.gdf".WrapInDoubleQuotes()}");
                writer.WriteLine("}");
    
                foreach (var value in values)
                    writer.WriteLine($"\t\t{value.Key.WrapInDoubleQuotes()} {value.Value.WrapInDoubleQuotes()}");
            };
        }
    }
    
    static class StringExtensions
    {
        //Helper method but you could do this inline as well
        public static string WrapInDoubleQuotes ( this string source )
        {
            if (source == null)
                return null;
    
            if (!source.StartsWith("\""))
                if (!source.EndsWith("\""))
                    return "\"" + source + "\"";
                else
                    return "\"" + source;
            else if (!source.EndsWith("\""))
                return source + "\"";
    
            return source;
        }
    }


    Michael Taylor http://www.michaeltaylorp3.net

    umm having a issue with the wrappedinquotes() class 

    i tried all i know i had issue like this before and removing the this form it worked but this is giving me a problem and not sure how to resolve it 

    sorry to be a pain elfenliedtopfan5

    error is as follows 
    Error CS1061 'string' does not contain a definition for 'WrapInDoubleQuotes' and no accessible extension method 'WrapInDoubleQuotes' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
    Monday, July 8, 2019 4:10 PM
  • It looks like, based upon your screenshot, that you took the method and tried to put it into the class you were already defining (given the field declarations after it). This is an extension method and extension methods must be in static classes. In my posted code I had created a `StringExtensions` static class. Put that entire class into your project, don't try to extract the method out of it.

    Michael Taylor http://www.michaeltaylorp3.net

    Monday, July 8, 2019 4:31 PM
    Moderator
  • Michael's solution is rather more clever than it needs to be.  His KEY POINT is quite correct, though; if you need the strings to be wrapped in quotes when you write them out, then add them when you write them out.  Your internal representation should not have unnecessary extra quotes.

        writer.WriteLine( "\"" + smgwep["displayName"] + "\": (\"bulledweapon.gdf\")");
        foreach( var entry in smgwep )
            writer.WriteLine("        \"{0}\" \"{1}\", entry.Key, entry.Value );


    Tim Roberts | Driver MVP Emeritus | Providenza &amp; Boekelheide, Inc.

    Monday, July 8, 2019 10:15 PM
  • Hi elfenliedtopfan2, 

    Thank you for posting here.

    For your question, you can also use a method to remove ‘\’ in keys and values in the Dictionary.

    Here’s the code:

            static Dictionary<string,string> Remove(Dictionary<string,string> dic)
            {
                List<string> listKey = new List<string>();
                List<string> listValue = new List<string>();
                foreach (string key in dic.Keys.ToList())
                {
                    listKey.Add(key.Replace("\\",""));  
                }
                foreach (string value in dic.Values.ToList())
                {
                    listValue.Add(value.Replace("\\", ""));
                }
                Dictionary<string, string> dic2 = new Dictionary<string, string>();
                for (int i = 0; i < listKey.Count; i++)
                {
                    dic2.Add(listKey[i],listValue[i]);
                }
                return dic2;
            }
            static void Main(string[] args)
            {
                var smgwep = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
    
                smgwep.Add("\"activate_mode\"", "\"hold\"");
                smgwep.Add("\"activate_with_primed_delay\"", "\"0\"");
                smgwep.Add("\"activatesSlam\"", "\"0\"");
                smgwep.Add("\"activatesSlamAsMelee\"", "\"0\"");
                smgwep.Add("\"activatesSlamAsPowerMelee\"", "\"0\"");
                smgwep.Add("\"activatesSlamAsPowerMeleeLeft\"", "\"0\"");
                smgwep.Add("\"acv_acog\"", "\"\"");
                smgwep.Add("\"acv_damage\"", "\"\"");
               smgwep.Add("\"acv_dualclip\"", "\"\"");
                smgwep.Add("\"acv_dualoptic\"", "\"\"");
    
                Dictionary<string, string> smgwep2 = Remove(smgwep);
            }

    Result:


    Hope it can help you.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Tuesday, July 9, 2019 7:01 AM
    Moderator