C#字典排序(按Key值、Value值顺序【升序】逆序【降序】排序)

字典的排序,简单做个笔记,方便查询(引用命名空间using System.Linq;):

Dictionary<int, int> tempDict = new Dictionary<int, int>();
var sortResult1 = from pair in tempDict orderby pair.Value descending select pair; //以字典Value值逆序排序[降序]
var sortResult2 = from pair in tempDict orderby pair.Key descending select pair; //以字典Key值逆序排序[降序]
var sortResult3 = from pair in tempDict orderby pair.Key ascending select pair; //以字典Key值顺序排序[升序]
var sortResult4 = from pair in tempDict orderby pair.Value ascending select pair; //以字典Value值顺序排序[升序]

总结:

  1. 需要注意的是,得到的排序结构sortResult1,2,3,4是一个迭代器 IOrderedEnumerable<> 了,不再是字典,如果这样写则是错误的:
Dictionary<int, int> sortResult1 = from pair in tempDict orderby pair.Value descending select pair; //以字典Value值逆序排序
  1. 如果字典的key值或Value值是引用类型的,可以根据根据引用类型中的某个字段来排序:
public class Info
{
	public int m_ID;
}
Dictionary<int, Info> tempDict = new Dictionary<int, Info>();
var sortResult1 = from pair in tempDict orderby pair.Value.m_ID descending select pair; //以字典Value值的字段 m_ID 逆序排序

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_42205218/article/details/105934030
 

C#中,可以有多种方式判断一个整数数组是否已经排序,下面是一些常见方法: 1. **直接比较**: 遍历数组,比较相邻的元素,如果它们不是按升序排列(对于升序数组),那么就说明数组未排序。例如: ```csharp bool IsSorted(int[] array) { for (int i = 0; i < array.Length - 1; i++) { if (array[i] > array[i + 1]) return false; } return true; } ``` 这里假设数组是升序排序,如果发现有逆序的情况则返回 `false`。 2. **使用SortedList或SortedArray**: 如果你对性能有一定要求,可以利用`System.Collections.Generic.SortedList` 或 `System.Linq.Enumerable.OrderBy` 对数组进行排序并检查结果,原数组就是有序的。 ```csharp bool IsSortedUsingSortedList(int[] array) { var list = new SortedList<int>(); foreach (var item in array) list.Add(item, item); // keyvalue 同样重要,此处仅做演示,实际应用key应该唯一 return list.Count == array.Length && list.Keys.SequenceEqual(array); } ``` 3. **使用Array.Sort()**: 如果允许修改原始数组,可以直接使用`Array.Sort()`方法,然后检查排序后的数组是否与原来的数组相等。 ```csharp bool IsSortedUsingArraySort(int[] array) { Array.Sort(array); return !Array.Exists(d => d != GetPreviousElement(array, d)); } private static T GetPreviousElement<T>(T[] array, T current) { // 获取当前元素前一个元素的位置 return array[array.IndexOf(current) - 1]; } ``` 如果所有元素都有前驱元素并且大小递增,那么返回 `true`,表示数组已排序
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值