如何根据指定优先级数组对C#字符串List进行排序?
根据自定义优先级列表排序字符串列表
实现思路
核心是通过元素在优先级列表中的索引值确定排序顺序:
- 先将优先级列表转换为字典(键为元素,值为对应索引),提升查找效率
- 排序时,存在于优先级列表的元素按索引升序排列;不存在的元素统一放在结果末尾
代码实现
方式1:使用LINQ(简洁直观)
// 定义优先级列表 List<string> priority = new List<string>() { "boss", "Project owner", "client", "manager", "client1", "client2 ", "Intern", }; // 待排序列表 List<string> arr = new List<string>(){ "client1", "boss", "manager", "unknown_user" }; // 构建优先级索引字典 var priorityIndexMap = priority .Select((item, index) => new { Item = item, Index = index }) .ToDictionary(x => x.Item, x => x.Index); // 执行排序 var sortedList = arr .OrderBy(item => priorityIndexMap.TryGetValue(item, out int index) ? index : int.MaxValue) .ToList(); // 输出结果:["boss", "manager", "client1", "unknown_user"]
方式2:使用List.Sort原地排序
// 定义优先级列表 List<string> priority = new List<string>() { "boss", "Project owner", "client", "manager", "client1", "client2 ", "Intern", }; // 待排序列表 List<string> arr = new List<string>(){ "client1", "boss", "manager", "unknown_user" }; // 构建优先级索引字典 var priorityIndexMap = priority .Select((item, index) => new { Item = item, Index = index }) .ToDictionary(x => x.Item, x => x.Index); // 自定义比较逻辑进行原地排序 arr.Sort((a, b) => { bool aHasPriority = priorityIndexMap.TryGetValue(a, out int aIndex); bool bHasPriority = priorityIndexMap.TryGetValue(b, out int bIndex); if (aHasPriority && bHasPriority) return aIndex.CompareTo(bIndex); // 都在优先级列表中,按索引排序 else if (aHasPriority) return -1; // a在列表中,b不在,a排前面 else if (bHasPriority) return 1; // b在列表中,a不在,b排前面 else return string.Compare(a, b); // 都不在时,按字符串默认顺序排序 }); // 排序后arr的值为:["boss", "manager", "client1", "unknown_user"]
说明
- 字典映射将元素索引的查找时间从O(n)优化到O(1),优先级列表较大时能显著提升性能
- 不在优先级列表中的元素,通过赋予
int.MaxValue作为索引(或比较器直接判定),确保排在所有存在元素之后 - 若需对多个不存在的元素保持原顺序(稳定排序),可结合LINQ的
OrderBy与原始索引,或调整比较器逻辑
内容的提问来源于stack exchange,提问作者gouravm
相关产品推荐
相关产品推荐

