How do you sort a list of JSONNodes by key value?
I have compiled a list of JSONNodes, each of which contains a key for "Title", "Date", "User" etc. How would I go about alphabetically sorting these nodes based on the "title" key value (or any key value for that matter)?
I've looked into using an "Lambda Expression", but I can't seem to wrap my head around it. In the expression "myList = myList.OrderBy(x => x.name), what would I use for "x"?
Note: I can retrieve the "title" key value for any JSONNode by using "myList[1]["title"], but I can't figure out how to compare the titles in each node to each other to figure out which comes first.
Any guidance would be very much appreciated. Thanks.
Answer by rmassanet · Sep 22, 2016 at 05:38 AM
In the lambda sorting function you mentioned, you don't set x, instead you receive x. So, the function will be called for every item of the list and, inside the function, the element will be called x. But sorting functions usually receive two elements, and you have to return an integer value indicating which one is "larger". Check this:
https://msdn.microsoft.com/library/system.icomparable(v=vs.110).aspx
On the other hand, you should not rely on JSON keeping the key order, because it is not guaranteed to be kept. If you need to keep order, use a JSON array (without keys) instead.
Your answer