我有以下JSON,我想知道是否可以使用Linq进行多次OrderBy
。
var body = @"[{
""portOfLoading"": ""GOT"",
""bookingResponses"":[{
""bookingNumber"": ""11"",
""comment"": ""LOFO"",
""customerReference"": ""3423462"",
""departureDate"": ""2017-04-10"",
""departureTime"": ""18:00"",
""description"": ""desc"",
""length"": ""7482"",
""netWeight"": ""12345"",
""plugin"": ""true"",
""resourceCode"": ""CONT26"",
""route"": ""GOTZEE"",
""status"": ""Price missing"",
""unitNumber"": ""ABC123"",
""width"": ""0""
}
]
}
,
{
""portOfLoading"": ""GOT"",
""bookingResponses"":[{
""bookingNumber"": ""3"",
""comment"": ""LOFO"",
""customerReference"": ""3423462"",
""departureDate"": ""2017-04-10"",
""departureTime"": ""18:00"",
""description"": ""desc"",
""length"": ""7482"",
""netWeight"": ""12345"",
""plugin"": ""true"",
""resourceCode"": ""CONT26"",
""route"": ""GOTZEE"",
""status"": ""Price missing"",
""unitNumber"": ""ABC123"",
""width"": ""0""
}
]
}
,{
""portOfLoading"": ""OUL"",
""bookingResponses"":[{
""bookingNumber"": ""7"",
""comment"": ""STANDBY"",
""customerReference"": ""3423462"",
""departureDate"": ""2017-04-10"",
""departureTime"": ""18:00"",
""description"": ""desc"",
""length"": ""7482"",
""netWeight"": ""12345"",
""plugin"": ""true"",
""resourceCode"": ""CONT26"",
""route"": ""OULZEE"",
""status"": ""Price missing"",
""unitNumber"": ""ABC123"",
""width"": ""0""
}
]
},{
""portOfLoading"": ""ZEE"",
""bookingResponses"":[{
""bookingNumber"": ""3"",
""comment"": ""STANDBY"",
""customerReference"": ""3423462"",
""departureDate"": ""2017-04-10"",
""departureTime"": ""18:00"",
""description"": ""desc"",
""length"": ""7482"",
""netWeight"": ""12345"",
""plugin"": ""true"",
""resourceCode"": ""CONT26"",
""route"": ""ZEEGOT"",
""status"": ""Price missing"",
""unitNumber"": ""ABC123"",
""width"": ""0""
}
]
},{
""portOfLoading"": ""GOT"",
""bookingResponses"":[{
""bookingNumber"": ""10"",
""comment"": ""STANDBY"",
""customerReference"": ""3423462"",
""departureDate"": ""2017-04-10"",
""departureTime"": ""18:00"",
""description"": ""desc"",
""length"": ""7482"",
""netWeight"": ""12345"",
""plugin"": ""true"",
""resourceCode"": ""CONT26"",
""route"": ""GOTZEE"",
""status"": ""Price missing"",
""unitNumber"": ""ABC123"",
""width"": ""0""
}
]
}
]";
到目前为止,我已经获得了“第一个”命令,就像这样:
JArray jsonVal = JArray.Parse(body);
JArray sortQuery = new JArray(jsonVal.OrderBy(obj => obj["portOfLoading"]));
"portOfLoading"
之后我想订购"bookingNumber"
。我尝试过使用ThenBy
等等,但从未让它工作过。感谢
答案 0 :(得分:3)
如果"bookingResponses"
中始终只有一个项目,请执行以下操作:
JArray jsonVal = JArray.Parse(body);
JArray sortQuery = new JArray(jsonVal.OrderBy(obj => obj["portOfLoading"])
.ThenBy(obj => int.Parse(obj["bookingResponses"].FirstOrDefault()?["bookingNumber"].ToString())));
添加Int.Parse
的原因是因为没有它,"bookingNumber"
将按照文本排序(作为字符串)而不是数字排序进行排序。导致订单:1,10,11,3。如果不确定值始终是有效整数(从而导致InvalidCastException
),可以执行this answer