一,OrderBy排序在MDSN中有两种使用方法,如下
1》第一种方法的使用,就是根据某个字段排序,使用默认的比较器(Comparer<T>.default),如下,由于Dictionary是继承IEnumerable的,所以这里可以使用Dictionary作为排序集合,
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestDemo { class Program { static void Main(string[] args) { Dictionary<string, object> dic = new Dictionary<string, object>(); dic.Add("B", "2"); dic.Add("A", "1"); dic.Add("D", "4"); dic.Add("C", "3"); StringBuilder str1 = new StringBuilder(); var param1 = dic.OrderBy(x => x.Key).ToDictionary(x => x.Key, y => y.Value); foreach (string dic1 in param1.Keys) { str1.Append(dic1+","); } Console.WriteLine(str1.ToString()); Console.ReadKey(); } } }
2》第二种方法的使用,按使用指定的比较器按升序对序列的元素进行排序。如下(使用ASCII值排序的例子介绍)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestDemo { class Program { static void Main(string[] args) { Dictionary<string, object> dic = new Dictionary<string, object>(); dic.Add("B", "2"); dic.Add("A", "1"); dic.Add("D", "4"); dic.Add("C", "3"); StringBuilder str1 = new StringBuilder(); var param = dic.OrderBy(x => x.Key, new ComparerTest()).ToDictionary(x => x.Key, y => y.Value); foreach (string dic1 in param.Keys) { str1.Append(dic1); } Console.WriteLine(str1.ToString()); Console.ReadKey(); } } public class ComparerTest : IComparer<String> { public int Compare(String x, String y) { return string.CompareOrdinal(x, y); } } }
看下面这句的代码,不知道,大家有没有跟我一样的疑惑?如下
var param = dic.OrderBy(x => x.Key, new ComparerTest()).ToDictionary(x => x.Key, y => y.Value);
为什么这句话实例ComparerTest这个类就可以完成比较???
查询一遍第二个方法的源码,如下图
1,原来指定的比较器接收的是IComparer<TKey> comparer类型,而ComparerTest是继承 IComparer<TKey>实现的比较方法。
2,相当于IComparer<String> icomparer = new ComparerTest();(这里是显式转换和隐式,想了解可以看http://www.cnblogs.com/May-day/p/6856457.html),这里实现了IComparer中的Compare方法
3,最后OrderBy调用比较器,即是IComparer中的Compare,排序