简体   繁体   中英

C# - Get array values from object in Dictionary of type string, object

I have a dictionary of type which contains an array of objects which have two decimal property values. For clarity it looks like this:

How do I access the values of those Easting and Northing values ?

var coordinates =(Coordinates[])values["Coordinates"];
Console.WriteLine(coordinates[0].Easting);
Console.WriteLine(coordinates[0].Northing);

To get just two values:

  var easting = values["Coordinates"][0].Easting;
  var northing = values["Coordinates"][0].Northing;

Explanation: since values is a dictionary :

  values["Coordinates"]            - get value (i.e. array) of "Coordinates" key
  values["Coordinates"][0]         - get 1st item of the array of "Coordinates" key
  values["Coordinates"][0].Easting - get Easting property of ...

Let values be the Dictonary and the "Coordinates" is a Key inside it. So that we can access the associated values with this key by using values["Coordinates"] . In your case the value will be a collection(Array). So To access those values you need to Specify its index or you can iterate through the collection to get it's values. As you already said it was a Dictonary<string,Object> You need to cast the object to get the Business object. If so you can use The following snippet:

var currentEasting = (Coordinates[])(values["Coordinates"][0]).Easting;

If the collection is defined like Dictonary<string,Coordinates> then you need not to cast. Can access it directly like this:

 var currentEasting = values["Coordinates"][0].Easting;

You can also iterate through those Values; this code will help you to do that:

foreach (Coordinates Co in values["Coordinates"])
{
   // access each values 
   var someEasting = Co.Easting
}

It is a bit unclear how the dictionary is defined. If it is defined as Dictionary<string, object> , you will either have to use reflection to get data from the value, or you will have to do a hard-coded cast:

var coords = (Coordinates[])values["Coordinates"];
var firstEast = coords[0].Easting;

This will of course fail if the object is not of type Coordinates.

If the dictionary is defined as Dictionary<string, Coordinates[]> , then it is simple:

var firstEast = values["Coordinates"][0].Easting;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM