GroupBy(TSource, TKey, TResult) 方法 (IEnumerable(TSource), Func(TSource, TKey), Func(TKey, IEnumerable(TSource), TResult))
 本文章是由機器翻譯。 將指標移到文章內的文字上方即可查看原文。 其他資訊。 譯文 原文

# Enumerable.GroupBy<TSource, TKey, TResult> 方法 (IEnumerable<TSource>, Func<TSource, TKey>, Func<TKey, IEnumerable<TSource>, TResult>)

.NET Framework (current version)

## 語法

```public static IEnumerable<TResult> GroupBy<TSource, TKey, TResult>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TKey, IEnumerable<TSource>, TResult> resultSelector
)
```

source

keySelector

resultSelector

#### 傳回值

Type:

TResult 型別項目的集合，其中每個項目都代表群組及其索引鍵的投影。

#### 類型參數

TSource

source 之項目的型別。

TKey

keySelector 所傳回之索引鍵的型別。

TResult

resultSelector 所傳回之結果值的型別。

## 範例

```class Pet
{
public string Name { get; set; }
public double Age { get; set; }
}

public static void GroupByEx3()
{
// Create a list of pets.
List<Pet> petsList =
new List<Pet>{ new Pet { Name="Barley", Age=8.3 },
new Pet { Name="Boots", Age=4.9 },
new Pet { Name="Whiskers", Age=1.5 },
new Pet { Name="Daisy", Age=4.3 } };

// Group Pet objects by the Math.Floor of their age.
// Then project an anonymous type from each group
// that consists of the key, the count of the group's
// elements, and the minimum and maximum age in the group.
var query = petsList.GroupBy(
pet => Math.Floor(pet.Age),
(age, pets) => new
{
Key = age,
Count = pets.Count(),
Min = pets.Min(pet => pet.Age),
Max = pets.Max(pet => pet.Age)
});

// Iterate over each anonymous type.
foreach (var result in query)
{
Console.WriteLine("\nAge group: " + result.Key);
Console.WriteLine("Number of pets in this age group: " + result.Count);
Console.WriteLine("Minimum age: " + result.Min);
Console.WriteLine("Maximum age: " + result.Max);
}

/*  This code produces the following output:

Age group: 8
Number of pets in this age group: 1
Minimum age: 8.3
Maximum age: 8.3

Age group: 4
Number of pets in this age group: 2
Minimum age: 4.3
Maximum age: 4.9

Age group: 1
Number of pets in this age group: 1
Minimum age: 1.5
Maximum age: 1.5
*/
}

```

## 版本資訊

Universal Windows Platform

.NET Framework

Portable Class Library

Silverlight

Windows Phone Silverlight

Windows Phone