一,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,排序