-1

I want to access key from value. and I am able to access value from key. My json file look as

{
    "screen": {
        "0": "42x11",
        "1": "16x16",
        "2": "40x30",
        "3": "32x32",
        "4": "42x32",
        "5": "48x32",
        "6": "60x40",
        "7": "150x40",
        "8": "84x48"
    },
    "os": {
        "0": {
            "versions": {
                "1": {
                    "name": "10"
                },
                "2": {
                    "name": "8"
                },
                "3": {
                    "name": "7"
                }
            },
            "name": "Windows"
        }
    },
    "app": {
        "1": {
            "name": "javaScript1",
            "versions": {
                "1": {
                    "name": "1.0"
                }
            }
        }
    }

} 

I have parsed the file with the help of JavaScriptSerializer as.

public void deserialize_metadata()
{
   using (StreamReader r = new StreamReader("C:\\Users\\vikash.kumar\\Desktop\\metadatainfo.json"))
   {
        var json = r.ReadToEnd();
        var jss = new JavaScriptSerializer();
        var dict = jss.Deserialize<Dictionary<string, dynamic>>(json);
        Console.WriteLine("dict" + dict["screen"]["0"]);    //o/p - 42x11
        Console.WriteLine("dict" + dict["app"]["1"]["name"]); //o/p - javaScript1
      }
}

It works fine when we want to access value from key.

How we can access key from value by this process?

Vikash Kumar
  • 31
  • 11
  • In that case you should add the information into the question. – Ankush Aug 21 '18 at 09:32
  • Okk Ankush I have mentioned in edit – Vikash Kumar Aug 21 '18 at 09:34
  • 1
    @VikashKumar And why not? – Patrick Hofman Aug 21 '18 at 09:38
  • @PatrickHofman I have tried to use as dict["screen"].value then .value was throwing error – Vikash Kumar Aug 21 '18 at 09:40
  • What error....? – Patrick Hofman Aug 21 '18 at 09:40
  • I have used as **if(dict["screen"].value.equals("42x11"))** and exception occured as **Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.Collections.Generic.Dictionary' does not contain a definition for 'value'' ** – Vikash Kumar Aug 21 '18 at 09:46
  • `Value` and `value` are different, C# is **case sensitive**. Also `dict["screen"]` should already return the "value" – Rafalon Aug 21 '18 at 09:47
  • @Rafalon then also same error occurred with Value – Vikash Kumar Aug 21 '18 at 09:51
  • @Rafalon if i use just dict["screen"] in Console.WriteLine then ** System.Collections.Generic.Dictionary`2[System.String,System.Object] ** get printed – Vikash Kumar Aug 21 '18 at 09:56
  • 2
    There's no such thing as `var` type. – Damien_The_Unbeliever Aug 21 '18 at 09:58
  • @Damien_The_Unbeliever How do you mean? If you mean where he's calling `var json = r.ReadToEnd();` in C#? This is strongly-typed because `ReadToEnd()` returns a string, so the type of `json` at compile time is `string`. Are you suggesting this might be contributing to the problem? https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var – Trevor Aug 21 '18 at 14:08
  • @Trevor - 4 hours ago, the OP removed their edit stating "There is no option to use .value and .key property in variable of var type.". It was to this I was objecting. It seemed to indicate they were at the point of confusion, often reached with people first learning about `var` in C# that it's somehow a different type rather than being a compiler trick that still leads to an actual type being selected for the variable. – Damien_The_Unbeliever Aug 21 '18 at 14:10
  • @Damien_The_Unbeliever Fair enough, I didn't see it before the edit. I completely agree that it suggests confusion over how `var` works. – Trevor Aug 21 '18 at 14:14
  • Thanks guys my problem got sorted by Rafalon's answer – Vikash Kumar Aug 21 '18 at 14:40

1 Answers1

0

From the duplicate, try: dict["screen"].FirstOrDefault(x => x.Value == "42x11")?.Key

I added ?. to take care of the possibility that .FirstOrDefault can return null if there's no match. This way it won't throw an exception but only return null.

Edit

Console.WriteLine((dict["screen"] as Dictionary<string, dynamic>)
                      .First(x => x.Value == "16x16").Key);
Rafalon
  • 4,450
  • 2
  • 16
  • 30
  • **Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type** error is showing at x=>x.value == "42x11" – Vikash Kumar Aug 21 '18 at 10:05
  • Oh right, that's because of the `dynamic` you used in your json deserializer. Maybe you could create a class that matches your json's format and explicitly tell that `dict["screen"]` is a `Dictionary` or just try to cast it this way (`var scr = dict["screen"] as Dictionary;` then `scr.FirstOrDefault(...)`) – Rafalon Aug 21 '18 at 10:07
  • Okay but how we can express app then,, – Vikash Kumar Aug 21 '18 at 10:09
  • You could do it like that: `Console.WriteLine((dict["screen"] as Dictionary).FirstOrDefault(x => x.Value == "16x16").Key);` – L_J Aug 21 '18 at 10:11
  • @VikashKumar this is a different question, but if your json isn't really dynamic, then maybe you should consider having a class with `screen`, `os`, and `app` **fields** having respectively `Dictionary`, `Dictionary` and `Dictionary` **types**. You would then access `dict.screen` instead of `dict["screen"]`. Or you could go further and completely remove `dynamic` – Rafalon Aug 21 '18 at 10:14
  • Thanks my problem is solved – Vikash Kumar Aug 21 '18 at 10:23