How do i set/retrieve value from dictionary in list? - c#

So I am able to retrieve the elements.handle but i am unable to retrieve elements.handle~. Is there any possible way to do so?
I've tried escape character elements['handle\~'] but it does not seem to work
{"elements":[{"handle":"urn:li:emailAddres:7440721026","handle~":{"emailAddress":"abc#gmail.com"}}]}

Since the value you are looking for (abc#gmail.com) is nested a few layers deep. If you want to retrieve it, you'll need to access it accordingly.
var data = "{\"elements\":[{\"handle\":\"urn:li:emailAddres:7440721026\",\"handle~\":{\"emailAddress\":\"abc#gmail.com\"}}]}";
dynamic x = JsonConvert.DeserializeObject(data);
// x is an object with one property: elements
Console.WriteLine($"x: {x}");
// x.elements is a List (based on your question)
Console.WriteLine($"x.elements: {x.elements}");
// x.elements[0] is a Dictionary (based on your question)
Console.WriteLine($"x.elements[0]: {x.elements[0]}");
// x.elements[0]["handle~"] is another Dictionary
Console.WriteLine($"x.elements[0][handle~]: {x.elements[0]["handle~"]}");
// x.elements[0]["handle~"]["emailAddress"] is the value you want
Console.WriteLine($"x.elements[0][handle~][emailAddress]: {x.elements[0]["handle~"]["emailAddress"]}");
That means x.elements[0]["handle~"]["emailAddress"] should get you abc#gmail.com.

Related

How do I iterate through items in a json object and retrieve a specific value in C#?

I have a json string that I would like to iterate through to retrieve a specific value. In this object, there are multiple items, each with the same elements. What i am trying to do is search through each item for its request_item.u_requested_for.user_name, and compare it to a different value. If it does NOT match, move on. If it does match, then i want to retrieve the request_item.u_requested_for.sys_id value. Additionally, the size of the json will not always be the same. Sometimes there will be 5 elements, other times 20. How can I loop through each item, do the comparison, and then retrieve the other value that I need?
I've played around with this using other ideas I've found, but I'm unable to really get it working. First, should i parse the string into an object using JObject.Parse()? Or should I continue working with this as as string?
I've tried using a JsonTextReader to read through each line, but I'm unsure how I would retrieve the value I need once I find the item that matches the criteria.
{
"result": [
{
"request_item.sys_id": "db6e3306dbc3ef8c791a777a8c961986",
"request_item.u_requested_for.sys_id": "8416ccb3dba9df8c1ddee3a84b961911",
"request_item.u_requested_for.user_name": "H298956"
},
{
"request_item.sys_id": "e5990f89db47ebc8bd663ebd7c96198f",
"request_item.u_requested_for.sys_id": "878ce1d5dbcd0300cc78dd0b5e961987",
"request_item.u_requested_for.user_name": "E092733"
},
{
"request_item.sys_id": "87970c08db4be388791a777a8c9619ee",
"request_item.u_requested_for.sys_id": "484a1cf5db5f83c04f6489584b961952",
"request_item.u_requested_for.user_name": "H281111"
}
]
}
In this case, I want to iterate through each item and look for the value "H281111". Once I find that value, I want to extract the "request_item.u_requested_for.sys_id value", which in this case is "484a1cf5db5f83c04f6489584b961952".
Depending on your requirements, you may want a much quicker and dirtier solution than Michaƫl's. If the contents of this JSON string are used in multiple places in your application, I urge you to write the classes and deserialize properly as he suggests. You'll be glad you did.
But if you only need one value from this JSON string in one place, this will work.
var jobj = JObject.Parse(json);
var user_name = "H281111";
var sys_id = jobj["result"]
.Where(r => (String)r["request_item.u_requested_for.user_name"] == user_name)
.Select(r => (String)r["request_item.u_requested_for.sys_id"])
.FirstOrDefault();
Elphas Tori suggests the following improvement using the ?[] (null-conditional element access) operator:
var sys_id2 = (string)jobj["result"]
.FirstOrDefault(r =>(string)r["request_item.u_requested_for.user_name"] == user_name)
?["request_item.u_requested_for.sys_id"];
If that LINQ code looks too much like gibberish to you, you can use a more conventional loop approach:
foreach (var r in jobj["result"])
{
// etc.
}
I think you should have a class representing the objects in this Json file, deserialize the Json file into your class and then use LINQ to find what you need in your list of objects.
Result would be an array of requestItem
Request item would have the following fields :
sys_id
u_requested_for (Class)
Requested for would have the following fields :
sys_id
user_name
You can even be fancy and use a base class that has sys_id in it to save some time.
You need to deserialize this into POCO objects to iterate them. Here you can find an example how to implement it.

How to handle data from nested dictionary in C#

Im have setup a nested Dictionary as follows:
static Dictionary<string, Dictionary<UInt32, TClassType> > m_dictionary = new Dictionary<string, Dictionary<UInt32, TClassType>>();
The "TClassType" contains three attributes:
Title (string)
code (uint)
Address (string)
I add value to this nested structure as follows:
TClassType newEntry = new TClassType(s_title, ui_code, s_address)
if (! m_dictionary.ContainsKey(s_title))// check as the same s_title can occur multiple times but have different ui_code and s_address values
{
m_dictionary.Add(s_title, new Dictionary<uint, TClassType>());
}
m_dictionary[s_title].Add(ui_code, s_address);
Now my question is what is a good way to access all of the values for a specific key [s_title]?
the key [s_title] will contain many items within the nested Dictionary, and for a unique [s_title] entry I would like to obtain all of the relevant keys and values related to this outter key from within the nested Dictionary.
Sorry I hope that's not confusing, I find it as hard to ask as I do trying to implement.
Thank you all in advance
Try this:
if (m_dictionary.Contains(s_title))
foreach(TClassType entry in m_dictionary[s_title].Values)
// Do something with the entry.
Have you used linq before? This would be a prime usage for groupby. What you're doing adds a level of convolution.
With your current setup if you have a list of TClassType you would be able to use the linq where expression to grab only those with the title you are looking for and then the ui_code you need.
Edit for example (I was on mobile before which is hard to code on :))
IEnumerable<TClassType> entries = entriesList;//whatever you use to populate the entries
var titles = entries.Where(x=> x.s_title == "Title you're looking for").Distinct();

How to read an array of objects

I have a C# list of objects and I'm trying to access its nested object. Here's the structure from Visual Studio's debugger (sorry I can't embed images since I'm a newbie to the site):
>product.Product {Product.AxdEntity_Product_EcoResProduct[1]}
>> - [0] {Product.EcoResProductMaster} // #1 - Please note curley braces
>>> - [Product.EcoResProductMaster] // #2 - Please note brackes
>>> + base {Product....
>>> + ModelingPolicy
>> + Identifier
To access the properties in #1, I would do the following:
var prod = product.Product[0];
Then I can access "Identifier" as such:
var identifier = prod.Identifier[0]...
To access the properties in #2 (such as ModelingPolicy), I'm not sure how to go about it:
var prod = product.Product[0][WhatShouldGoHere?].ModelingPolicy[0] ...?? I need help here
Eventually, I'd like to access the ModelingPolicy[0] like I did with prod.Identifier[0].
The Product class is being returned from a web service and I don't have access to its definition. At least I don't think I do.
Thank you for any guidance!
Looks to me like:
var ecoResProductMaster = product.Product[0].EcoResProductMaster; // Product type
var modelingPolicy = ecoResProductMaster.ModelingPolicy;
Have you tried this?
var productList = product.ToList()
foreach(var prod in productList)
{
var identifier = prod.identifier
foreach (var modelingPolicy in identifier.ModelingPolicy)
{
//do somthing with modeling policy
}
//do more stuff with product
}
As an aside please sort your naming conventions out. Having an array called product that contains a number of Product objects is just confusing
It's difficult to tell what you're going for here. Is this a List or array?
If it is a list then you can just foreach through the list to access each object.
Like if you have
List<SomeObject> someObjectList = new List<SomeObject>();
Then after you add a bunch of SomeObjects to the List you can just access the SomeObjects in a foreach loop.
foreach (SomeObject s in someObjectList)
{
// then to access nested objects
var n = s.SomeNestedObject;
// do something with n
}
Thanks all for your input. The answer from SmartDev helped me access the objects in the inner array. To do this, simply do the following:
var productMaster = (EcoResProductMaster)product.Product[0];
var modelingPolicy = productMaster.ModelingPolicy[0];
Of course, this is assuming that only one object is returned in the array, hence "[0]" but this should eventually go inside a foreach loop.
What I learned was if an object is returned without an index such as //#2 as noted above, a type cast should allow me to access it. However, if an index is returned such as //#1, then using [0] will allow me to access its properties.

Accessing properties of objects within a List<T>

I'm trying to use a property of individual object instances stored within a List<T> object, but I can't seem to access the properties directly.
I have an object (sportsCarVehicle) which stores a user-defined name (strVehicleName) (amongst other properties, but that's not important) within itself. The object is then stored within a List<sportsCarVehicle> object called sportsCarVehicleStorage.
I need to access every instance of sportsCarVehicle in List<sportsCarVehicle> and pass the value of strVehicleName to a combo box on a form.
I assume I'll need some kind to loop to cycle through each instance and pass the name to the combo box, but my main issue is not being able to access the property I need. The sportsCarVehicle instances have no reference-able name.
One more thing I should note: the constructor for sportsCarVehicle is called within the sportsCarVehicleStorage.Add() method.
Any suggestions on how I could do this?
Cant you do this
List<string> lst = new List<string>{"Hello", "World"};
int len = lst[0].Length;
Here .Length is a property of string. As long as that property is public we can access it.
In your case
List<sportsCarVehicle> sportsCarVehicleStorage = new List<sportsCarVehicle>();
// Some code to populate list.
mycombobox.Items = sportsCarVehicleStorage
.Select(x => x.strVehicleName).ToArray();
Make Sure property strVehicleName is public in that class.
You can use foreach to loop through the list, assigning each member of the list to a named variable, like:
foreach (sportsCarVehicle scv in sportsCarVehicleStorage)
{
//scv is the name of the currently looping sportsCarVehicle object
//use scv.strVehicleName to access the property.
myComboBox.Items.Add(scv.strVehicleName);
}
foreach (SportsCarVehicle car in myListName)
{
//do stuff here
}
That's the most basic example, you can use PLINQ etc. to do it in a more streamlined way.
An alternative could be to bind the list of sportsCarVehicle directly to the comboBox, for example:
List<sportCarVehicle> sportsCarVehicleStorage= new List<sportsCarVehicle>;
// Set up list content here
// ...
myComboBox.DataSource = sportsCarVehicleStorage;
myComboBox.DisplayMember = "strVehicleName";

How could I determine if an array contains a value at a particular index?

I have an array with values at meaningful indices. How can I tell if a particular there is a value at a particular element?
Array.Exists() is the closest I've found, but it looks overcomplicated for what I want, so I'm curious to know if it's really the best way.
UPDATE
OK, so I have an array of objects:
ImageGroup[] Images;
And the index of the elements corresponds to a feature of that item. In this case, the index refers to a value within the filename of the original image. When I come across a filename, I want to check if an element exists at the corresponding index and create one if not.
So I want to know if Images[someInt] exists.
Updated
With the last update this looks more like a dictionary (unless you're going in numerical order and not where "1,2,5" may have been populated, but 3,4 are absent and need to be created). If this is something where index could potentially skip, I would recommend a dictionary:
Dictionary<Int32,Image> images = new Dictionary<Int32, Image>();
// populated previously
Int32 needle = GetIndexOfImage(newImage);
if (!images.ContainsKey(needle))
images.Add(needle, newImage);
Then, once you're done populating, you can then re-reference the item by index in the following fashion:
images[specificIndex]
Once more, you can retrieve all the elements stored using the following as well:
images.Values
Some resources:
Dictionary
Dictionary.ContainsKey
First response:
if (a[index] == interesting) ....
After the Edit(s):
int index = GetIndexFromFilename(filename);
// if (Images[index] != null && Images[index] == interesting) ....
if (Images[index] == null)
Images[index] = CreateImage(filename);
But you should probably just use a Dictionary<string, Image> and use filename as the Key.
It sounds like what you're looking for is the functionality of a dictionary. It would be extremely helpful if you posted how you're populating your array, and how you want to be able to index it. From what I can gather, this is how I would implement...
Dictionary<SomeEnum, ImageGroup> images = new Dictionary<SomeEnum, ImageGroup>();
foreach(SomeEnum enumValue in Enum.GetValues(typeof(SomeEnum)))
{
ImageGroup group = BuildImageGroup();
images.Add(enumValue, group);
}
then you can do:
...
if(images.ContainsKey(SomeEnum.SomeValue))
return images[SomeEnum.SomeValue];
else
return DoSomethingFancy();
If you have multiple image groups for a single enum value (collisions), then you can use a collection of ImageGroups in the dictionary, like this:
Dictionary<SomeEnum, ImageGroup[]>

Categories

Resources