【问题标题】:use OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>)使用 OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>)
【发布时间】:2012-08-14 07:35:49
【问题描述】:

想通过例子来理解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”,key是“Age”,pet => pet.Age是

 Func<TSource, TKey>?

谢谢。

【问题讨论】:

    标签: c# linq c#-4.0


    【解决方案1】:

    不,TSourcePet 类型,TKeyint 类型。所以不使用类型推断,你会有:

    IEnumerable<Pet> query = pets.OrderBy<Pet, int>(pet => pet.Age);
    

    TSourceTKey 是该方法的generic type parameters。你可以把它们想象成类的泛型类型参数......所以在List&lt;T&gt; 中,T 是类型参数,如果你写:

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

    那么这里的类型参数string(所以你可以说T=string在这种情况下,以一种手动的方式)。

    您的情况的不同之处在于编译器根据方法调用参数为您推断类型参数。

    【讨论】:

    【解决方案2】:

    不,从msdnEnumerable.OrderBy&lt;TSource, TKey&gt; Method (IEnumerable&lt;TSource&gt;, Func&lt;TSource, TKey&gt;

    • TSource

      源元素的类型。

    • TKey

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

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

      从元素中提取键的函数。

    所以TSource = Pet; TKey = int

    【讨论】:

    【解决方案3】:

    Jon Skeet 的book 非常彻底地介绍了这些细节。话虽如此,在这种情况下,使用 Visual Studio 中的鼠标浮动工具查看 Generic 的播放情况很有用。

    【讨论】: