How Can I Sort JArray For Value

How can I sort JsonArray for value?

As-is

[
	{
		"name": "BBB",
		"value": "3"
	},
	{
		"name": "AAA",
		"value": "1"
	},
	{
		"name": "CCC",
		"value": "2"
	}
]

To-be

[
	{
		"name": "AAA",
		"value": "1"
	},
	{
		"name": "CCC",
		"value": "2"
	},
	{
		"name": "BBB",
		"value": "3"
	}
]

I’ve tried according to this,
https://stackoverflow.com/questions/39408158/c-sharp-sort-json-for-value

Assign listOb = listOb.OrderBy(x => x.value)

But error popped up.

‘Need an expression’

Hi.

the => is a syntax of C#. You are probably in a vb .net mode of Studio, so need the correct syntax.

So you can do same thing but use Function(x) instead of x =>, which basically declares that variable to be used inside the parenthesis scope.

Also, to get the value parameter, use it in parenthesis (similar to a dictionary or datarow), x(“Value”).

Lastly, since the values are numbers, you need to sort them numerically.

Something like this maybe?:

listOb.OrderBy(Function(x) Convert.ToInt32(x("Value")) )

To go further, you could make sure the value is a number when sorting:

listOb.OrderBy(Function(x) If(IsNumeric(x("Value")), Convert.ToInt32(x("Value")), 99999) )

I have not tested your example with this, but hopefully it gets you in the right direction.

Regards.

1 Like

It doesn’t work in my case. But I tried another way to resolve a problem. Thank you.

2 Likes

Hi @swseo ,

can you please let me know how did you sort your JArray by value.

Thanks,
@monuprasad.gaud