GroupBy 拡張メソッドで要素をグループ化する
GroupBy 拡張メソッドは指定されたキーで分類分けします。同様の機能として ToLookup 拡張メソッドがあります。これらの違いに関しては「3.1.49 ToLookup 拡張メソッドで要素をグループ化する」を参照してください。
namespace Tips_Linq
{
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var numbers = new int[] { 1, 2, 3, 1, 3, 2, 4, 2 };
Console.WriteLine("コレクションの要素は {{ {0} }} です。", string.Join(", ", numbers));
var numberGroups = numbers.GroupBy(x => x);
foreach (var group in numberGroups)
{
Console.WriteLine(group.Key + " が " + group.Count() + " 個あります。");
}
Console.ReadKey();
}
}
}
次は以下のような Person クラスでグループ化してみましょう。
namespace Tips_Linq
{
using System;
///
/// 人物データを表します。
///
public class Person
{
///
/// 氏名を取得または設定します。
///
public string Name { get; set; }
///
/// 更新日付を取得または設定します。
///
public DateTime Date { get; set; }
}
}
例えば Date プロパティの年で分類分けする場合は次のようなコードになります。
namespace Tips_Linq
{
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var people = GetPeople();
var groups = people.GroupBy(x => x.Date.Year);
foreach (var group in groups)
{
Console.WriteLine("== {0} 年の人 =====", group.Key);
foreach (var person in group)
{
Console.WriteLine(person.Name);
}
}
Console.ReadKey();
}
///
/// 人物コレクションの列挙子を取得します。
///
///
static IEnumerable<Person> GetPeople()
{
yield return new Person() { Name = "田中 淳平", Date = new DateTime(2011, 5, 2) };
yield return new Person() { Name = "鈴木 ほのか", Date = new DateTime(2014, 3, 24) };
yield return new Person() { Name = "小池 哲司", Date = new DateTime(2015, 6, 13) };
yield return new Person() { Name = "恩田 進", Date = new DateTime(2011, 7, 28) };
yield return new Person() { Name = "中津山 亜希子", Date = new DateTime(2015, 9, 9) };
}
}
}
グループ化されたあとは Key プロパティで分類の値を取得できます。
ところで、グループ化に指定するキーがカスタムクラスの場合、キーが一致しているかどうか評価するための比較子が必要となります。このことについて調べるために、Person クラスを次のように定義し直します。
namespace Tips_Linq
{
using System;
///
/// 人物データを表します。
///
public class Person
{
///
/// 氏名を取得または設定します。
///
public string Name { get; set; }
///
/// 更新日付を取得または設定します。
///
public DateTime Date { get; set; }
///
/// 子どもを取得または設定します。
///
public Person Child { get; set; }
}
}
Person クラスの中に Child という名前の Person クラスのプロパティを追加しました。この子どもの名前が一致しているかどうかで分類分けするために、次のような比較子を定義します。
namespace Tips_Linq
{
using System.Collections.Generic;
///
/// Person クラスに対する等値比較子を表します。
///
public class PersonComparer : IEqualityComparer<Person>
{
public static readonly PersonComparer NameComparer = new PersonComparer();
///
/// 指定された Person クラスのオブジェクトが等しいかどうかを確認します。
///
/// "x">比較基準を指定します。
/// "y">比較対象を指定します。
///
Name プロパティが等しい場合に true を返します。 public bool Equals(Person x, Person y)
{
if ((x == null) && (y == null)) return true;
if ((x == null) || (y == null)) return false;
return x.Name == y.Name;
}
///
/// ハッシュ値を取得します。
///
/// "obj">ハッシュ値を算出するオブジェクトを指定します。
///
算出したハッシュ値を返します。 public int GetHashCode(Person obj)
{
return obj.Name.GetHashCode();
}
}
}
Child プロパティが null である場合も想定しているため、Equals() メソッド中で null 判定を入れています。
これらを使って GroupBy 拡張メソッドを使ってみましょう。
namespace Tips_Linq
{
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var people = GetPeople();
var groups = people.GroupBy(x => x.Child, PersonComparer.NameComparer);
foreach (var group in groups)
{
var name = group.Key != null ? group.Key.Name : "NULL";
Console.WriteLine("== 子どもの名前が {0} の人 =====", name);
foreach (var person in group)
{
Console.WriteLine(person.Name);
}
}
Console.ReadKey();
}
///
/// 人物コレクションの列挙子を取得します。
///
///
static IEnumerable<Person> GetPeople()
{
yield return new Person() { Name = "田中 淳平", Date = new DateTime(2011, 5, 2), Child = new Person() { Name = "田中 清美" } };
yield return new Person() { Name = "鈴木 ほのか", Date = new DateTime(2014, 3, 24), Child = new Person() { Name = "田中 清美" } };
yield return new Person() { Name = "小池 哲司", Date = new DateTime(2015, 6, 13), Child = new Person() { Name = "小池 真司" } };
yield return new Person() { Name = "恩田 進", Date = new DateTime(2011, 7, 28) };
yield return new Person() { Name = "中津山 亜希子", Date = new DateTime(2015, 9, 9) };
}
}
}
ちなみに GroupBy 拡張メソッドの第 2 引数を省略した場合は次のような結果になります。
「田中 清美」という名前は同じですが、インスタンスが異なるので分類としては同じになりません。裏を返せば、同じインスタンスで定義した Child プロパティであれば comparer を指定することなく分類することができます。分類分けするキーがプロパティ値なのかインスタンスなのかを理解した上で使いましょう。
GroupBy 拡張メソッドには他にもオーバーロードが用意されています。非常に複雑なので少し整理してみましょう。
入力引数にはそれぞれ keySelector、elementSeoector、resultSelector、comparer という名前が付いており、それぞれの処理は次のような順序になります。
elementSelector という入力引数は Func<TSource, TElement> という型の関数を指定します。
resultSelector へ渡すシーケンスを元のシーケンスから射影します。省略した場合は元の型と同じものがシーケンスとなって resultSelector へ渡されます。
resultSelector という入力引数は Func<TKey, IEnumerable<TSource>, TResult> という型の関数を指定します。これまでは resultSelector 入力引数を省略していたため、戻り値は各要素が IGroup<TSource, TSource> インターフェースのシーケンスでした。resultSelector 入力引数を使用することで分類分けしたキーを使用しながら戻り値の各要素を他の型に変換することができます。
Tweet