简体   繁体   中英

Similar method to valueForKeyPath:(Obj-C) in c#

I have list of dictionaries in c#. How to create array of items for specific key from dictionary? In objective-C there is valueForKeyPath: method.

Here is an example of the list with dictionaries:

 [
   { "id": 1546, "description": “test_1” }, 
   { "id": 2228, "description": “test_2” }, 
   { "id": 2762, "description": "test_3” }
 ]

and I would like to get:

 [ 1546, 2228, 2762 ] 

for key id .

Why don't you run a loop ex:

var list = new List<int>();
foreach(var dic in DictionaryList){
  if(dic.ContainsKey("id"))
    list.Add( dic["id"] );
}

First for loop is iterating through your list and grabbing each dictionary, the second for is graving each key value pair and you can then compare it to whatever is that you looking for. May be easier to do in a lambda expression, I just didn't have the time to write one up.

I think this is closer to what you were asking for. If I understand correctly you have a list of dictionaries and you trying to get a specific value out of each dictionary in the list. "ContainsKey" returns a bool, if its true then you can access that specific keyValue in the dictionary and add the value to a list or do whatever you want with it.

You can use this code:

NSMutableArray *arr;

for(int i=0;i<[givenArr count];i++){

NSDictionary *dic=givenArr[i];
[arr addObject:[dic valueForKey:@"id"]];
}
NSLog(@"%@",arr);

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