c# – 使用OrderBy(IEnumerable,Func)
发布时间:2020-12-16 00:05:00 所属栏目:百科 来源:网络整理
导读:我想通过这个例子来理解TSource的概念,Tkey. 我们有代码 class Pet { public string Name { get; set; } public int Age { get; set; } } public static void OrderByEx1() { Pet[] pets = { new Pet { Name="Barley",Age=8 },new Pet { Name="Boots",Age=4
我想通过这个例子来理解TSource的概念,Tkey.
我们有代码 class Pet { public string Name { get; set; } public int Age { get; set; } } public static void OrderByEx1() { Pet[] pets = { new Pet { Name="Barley",Age=8 },new Pet { Name="Boots",Age=4 },new Pet { Name="Whiskers",Age=1 } }; IEnumerable<Pet> query = pets.OrderBy(pet => pet.Age); foreach (Pet pet in query) { Console.WriteLine("{0} - {1}",pet.Name,pet.Age); } } /* This code produces the following output: Whiskers - 1 Boots - 4 Barley - 8 */ 我们可以说TSource是“宠物”,关键是“年龄”和宠物=> pet.Age是 Func<TSource,TKey>? 谢谢. 解决方法
不,TSource是Pet类型,TKey是int类型.所以不使用类型推断,你有:
IEnumerable<Pet> query = pets.OrderBy<Pet,int>(pet => pet.Age); TSource和TKey是该方法的generic type parameters.您可以将它们视为类的泛型类型参数…因此在List< T>中,T是类型参数,如果您编写: List<string> names = new List<string>(); 那么这里的类型参数是字符串(所以你可以说在这种情况下T =字符串,以手工波浪形式). 您的情况的不同之处在于编译器根据方法调用参数推断出类型参数. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |