I’ve got several classes generated from JSON code that I’m deserializing:
public class Rootobject
{
public Section[] sections { get; set; }
}
public class Section
{
public string base_label { get; set; } = string.Empty;
public Content[] contents { get; set; }
}
public class Content
{
// main properties
public int Index { get; set; }
public string File { get; set; } = string.Empty;
public string Label { get; set; } = string.Empty;
public string Type { get; set; } = string.Empty;
}
I created a new object and a variable to access the Contents of a specific Section:
public Rootobject editData = new Rootobject();
var itemData = editData.sections[x].contents;
The JSON gets deserialized in to editData
I want to reorder the Contents, sorting based on Index number–the catch is, I don’t want to create a new List, because editData
is being used to serialize back in to my original JSON file.
itemData.OrderByDescending(x => x.Index)
did not appear to do anything, and itemData.contents.Sort((i1, i2) => i1.Index.CompareTo(i2.Index));
throws an error (Cannot convert lambda expression to type ‘array’ because it is not a delegate type) … so I’m unsure how to approach this. Thanks!
7
itemData.OrderByDescending(x => x.Index)
did not appear to do anything
That depends on what you’re expecting it to do. What it does is return an ordered enumerable from the source data. You need to assign that returned result to something.
For example:
editData.sections[x].contents = editData.sections[x].contents.OrderByDescending(x => x.Index).ToArray();
This would order the contents of editData.sections[x].contents
and assign the result back to that same property. (Note the addition of ToArray()
, since OrderByDescending
will return an instance of IOrderedEnumerable<Content>
and your property is of type Content[]
.)