1

how can I sort Array in Object Array with element key ?

Please see picture for more info : Array in object Array

So for example in picture you can see we have 8 object now , so we want to sort 8 object with key in new array for example sort 8 object with "parentId" key in array or "categoryName" key in array !!!

But I think we have a problem because we can't access to key in new array !!!

So I think this code can't help to me :

 Array.Sort....

Now how can I sort object with array key like this ?

Kind regards

3 Answers 3

2

It is not obvious from your question, but the array you want to sort seems to contain dictionaries that represents object instances by having the same set of keys. To get access to the values you need to cast the array elements to the correct dictionary type (I assume it is Dictionary<String, String>). You can then use LINQ to sort by using the OrderBy clause:

var sortedByCategoryName = result
  .Cast<IDictionary<String, String>>()
  .OrderBy(d => d["categoryName"]);

The sorting will be based around string sorting because the values are strings. However, if you want to sort by say parentId (which is a number) you first need to perform a conversion:

var sortedByParentId = result
  .Cast<IDictionary<String, String>>()
  .OrderBy(d => Int32.Parse(d["parentId"]));

Note that the above code will throw exceptions if either a key is missing from the dictionary or, in the second example, if the value cannot be parsed as an integer.

Sign up to request clarification or add additional context in comments.

2 Comments

@ Martin Liversage : Thanks for info , I like to use from your code but i have a problem !!! I Use Like this : IDictionary<XmlRpcStruct, XmlRpcStruct>>() I can't use and i have a problem with this code : .OrderBy(d => Int32.Parse(d["parentId"])); cannot convert from 'CookComputing.XmlRpc.XmlRpcStruct' to 'string' do you have any idea ?
@Sam: I don't know about XmlRpcStruct and the only source of information about your data structures are you screenshot. However, you could try to do results.Cast<XmlPrcStruct>(). I'm guessing the XmlRpcStruct is a dictionary-like type and perhaps the type you store in the array.
2

If you use Lists you can sort like this:

List<objectName> yourList = yourArray.TypeOf<objectName>().ToList();
yourList.Sort((x,y) => x.yourKey.CompareTo(y.yourKey));

2 Comments

@Sam ...then put your array in a list.
@Toon Casteele & J.Steen : yeap Thanks :) :D
1

if you use linq you can do multiple levels of sorting

using System.Linq;

and

Array result = new Array(from item in your array order by item.parentId, item.categoryName select item);  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.