我有一个键值对列表,我想根据另一个数组中指定的顺序对其进行排序。
var requiredOrder = new String[] { "PH", "HH", "PR", "SR", "UN", "UD", "WD", "WE", "OT" };
var listToBeSorted = new List<KeyValuePair<string, string>>() {
new KeyValuePair<string, string>("A","PR"),
new KeyValuePair<string, string>("B","PH"),
new KeyValuePair<string, string>("C","HH"),
new KeyValuePair<string, string>("D","WD"),
new KeyValuePair<string, string>("E","OT"),
new KeyValuePair<string, string>("F","UN"),
.....
};
Run Code Online (Sandbox Code Playgroud)
“listToBeSorted”实际上是我为下拉列表获取的集合,该下拉列表需要根据“requiredOrder”数组按值排序。
requiredOrder您可以使用以下方法按数组中项目的索引进行排序Array.IndexOf()
listToBeSorted = listToBeSorted.OrderBy(x => Array.IndexOf(requiredOrder, x.Value)).ToList();
Run Code Online (Sandbox Code Playgroud)