简体   繁体   中英

sorting custom objects from array into dictionary by property

Is there an easy way to sort an array of custom objects (in this case Lists ) into a dictionary based on a particular property of each list.

[List1, List2, List3, List4, List5];

For example, each List object has an NSString type property, which can be either "MyList","Sent","Received"

How would I create a dictionary based on these properties so that I have a dictionary like so:

  • "MyList" -> array of lists with MyList as their type property [List1, List5];
  • "Sent" -> array of lists with Sent as their type property "Received" [List3;
  • "Received" -> array of lists with Received as their type property [List2, List4];

I'd really rather not loopthrough my entire array of List objects if possible

You need to iterate the array and build your dictionary. If the key isn't already there, create the array and add it to the dictionary, then add the new item to it.

You could alternately use predicates to filter the array into sub-arrays and build the dictionary like that but it's a similar amount of code (for a few options) and doesn't support automatic future expansion when you have another value for the key you're organising on.

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