OrderedDictionary может использоваться для сохранения порядка добавленных элементов или SortedDictionary для сортировки элементов по ключу .
Учитывая следующую модель:
public class MyClass
{
public string UniqueId { get; set; }
public string Value { get; set; }
}
И следующие экземпляры:
var first = new MyClass {UniqueId = "First", Value = "This"};
var second = new MyClass {UniqueId = "Second", Value = "That"};
var third = new MyClass {UniqueId = "Third", Value = "Foo"};
var fourth = new MyClass {UniqueId = "Fourth", Value = "Bar"};
Использование OrderedDictionary
var dictionary = new OrderedDictionary()
{
{ first.UniqueId, first },
{ second.UniqueId, second },
{ third.UniqueId, first },
{ fourth.UniqueId, first },
};
string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
Это сохранит порядокдобавленные предметы.Выходные данные json следующие:
{
"First": {
"UniqueId": "First",
"Value": "This"
},
"Second": {
"UniqueId": "Second",
"Value": "That"
},
"Third": {
"UniqueId": "First",
"Value": "This"
},
"Fourth": {
"UniqueId": "First",
"Value": "This"
}
}
Использование SortedDictionary
var first = new MyClass {UniqueId = "First", Value = "This"};
var second = new MyClass {UniqueId = "Second", Value = "That"};
var third = new MyClass {UniqueId = "Third", Value = "Foo"};
var fourth = new MyClass {UniqueId = "Fourth", Value = "Bar"};
var dictionary = new SortedDictionary<string, MyClass>
{
{ first.UniqueId, first },
{ second.UniqueId, second },
{ third.UniqueId, first },
{ fourth.UniqueId, first },
};
string json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
Это позволит отсортировать элементы по ключу (Fourth
это 2-й элемент, а не 4-й).Выходные данные json следующие:
{
"First": {
"UniqueId": "First",
"Value": "This"
},
"Fourth": {
"UniqueId": "First",
"Value": "This"
},
"Second": {
"UniqueId": "Second",
"Value": "That"
},
"Third": {
"UniqueId": "First",
"Value": "This"
}
}