コード例 #1
0
    public static void Test()
    {
        Basket b1 = new Basket();

        b1.AddFruit(new Banana()
        {
            Description =
                new FruitDescription(FruitSize.Medium, FruitColor.Blue)
        });
        b1.AddFruit(new Banana()
        {
            Description =
                new FruitDescription(FruitSize.Medium, FruitColor.Green)
        });
        Basket b2 = new Basket();

        b2.AddFruit(new Pear()
        {
            Description =
                new FruitDescription(FruitSize.Medium, FruitColor.Green)
        });
        List <Basket> source = new List <Basket>();

        source.Add(b1);
        source.Add(b2);
        //the main event - a query.
        List <Pair <Fruit, Basket> > result =
            (
                from basket in source
                from fruit in basket.GetFruits()
                select new Pair <Fruit, Basket>()
        {
            First = fruit, Second = basket
        }
            ).ToList();
        //a second results structure for fun
        ILookup <Type, Basket> resultByType = result.ToLookup
                                              (
            p => p.First.GetType(),
            p => p.Second
                                              );

        Console.WriteLine("Number of fruit: {0}",
                          result.Count);
        Console.WriteLine("Number of apples: {0}",
                          resultByType[typeof(Apple)].Count());
        Console.WriteLine("Number of baskets with apples: {0}",
                          resultByType[typeof(Apple)].Distinct().Count());
        Console.WriteLine("Number of bananas: {0}",
                          resultByType[typeof(Banana)].Count());
        Console.WriteLine("Number of baskets with bananas: {0}",
                          resultByType[typeof(Banana)].Distinct().Count());
    }