自分で作ったり提供したりするものは、まず自分自身で使ってみろろということです。自分じゃ使わないものなら人はいくらでも無責任にも無思考にもなれる。そういう投げやりな「サービス」やら「プロダクツ」なんて、だれだってイヤだ。自分が作り手と同時に利用者の立場になれば、ちゃんと使えるレベルのものを提供しようとします。

2010年7月15日木曜日

Linq-GroupBy

Linq言語のGroupBy機能を紹介します。

従来のSELECT文でGroupByをしていますが、Linq言語を利用したら簡単にできるようになりました、本当にありがたい技術です。

class Pet
{
    public string Name { get; set; }
    public int Age { get; set; }
}

// Uses method-based query syntax.
public static void GroupByEx1()
{
    // Create a list of pets.
    List<Pet> pets =
        new List<Pet>{ new Pet { Name="Barley", Age=8 },
                       new Pet { Name="Boots", Age=4 },
                       new Pet { Name="Whiskers", Age=1 },
                       new Pet { Name="Daisy", Age=4 } };

    // Group the pets using Age as the key value
    // and selecting only the pet's Name for each value.
    IEnumerable<IGrouping<int, string>> query =
        pets.GroupBy(pet => pet.Age, pet => pet.Name);

    // Iterate over each IGrouping in the collection.
    foreach (IGrouping<int, string> petGroup in query)
    {
        // Print the key value of the IGrouping.
        Console.WriteLine(petGroup.Key);
        // Iterate over each value in the
        // IGrouping and print the value.
        foreach (string name in petGroup)
            Console.WriteLine("  {0}", name);
    }
}

実行結果:
/*
 This code produces the following output:

 8
   Barley
 4
   Boots
   Daisy
 1
   Whiskers
*/

0 件のコメント:

コメントを投稿

ホームページ