使用 OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>)

3

我希望通过示例了解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 => pet.Age是宠物的年龄。
 Func<TSource, TKey>?

感谢您的请求。
3个回答

10
不,TSource 是类型 Pet,而 TKey 是类型 int。因此,如果不使用类型推断,你需要写成这样:
IEnumerable<Pet> query = pets.OrderBy<Pet, int>(pet => pet.Age);

TSourceTKey是该方法的泛型类型参数。您可以将它们视为类的泛型类型参数...因此,在List<T>中,T是类型参数,如果您编写:

List<string> names = new List<string>();

那么这里的类型参数string(因此你可以用手挥一挥说在这种情况下T=string)。

在您的情况下,编译器会根据方法调用参数为您推断类型参数的区别。


你的意思是代码中省略了 <Pet, int> 吗?这里的 Func 是什么? - user1108948
@Love:这是由编译器推断出来的。有关详细信息,请参阅MSDN上的通用方法:http://msdn.microsoft.com/en-us/library/twcad0zb.aspx - Jon Skeet

1

不是从msdn获取Enumerable.OrderBy<TSource, TKey> Method (IEnumerable<TSource>, Func<TSource, TKey>

  • TSource

    源元素的类型。

  • TKey

    keySelector返回的键的类型。 参数源类型:System.Collections.Generic.IEnumerable

    要排序的值序列。 keySelector类型:System.Func

    从元素中提取键的函数。

所以TSource = Pet; TKey = int


那么这里的 Func<TSource, TKey> 是什么? - user1108948
Func<TSource, TKey> 是一个用于从元素中提取键的 keySelector 函数。您可以在此处找到完整的函数描述:http://msdn.microsoft.com/en-us/library/bb534966.aspx - GSerjo

1

Jon Skeet的相当详细地涵盖了这些细节。话虽如此,在这种情况下,使用Visual Studio中的鼠标悬停工具可以很好地展示泛型的运作方式。

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接