計算機科学のブログ

LINQ and lambdas - Get Control of your data - IEnumerable, IGrouping, foreach, nest

Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 9(LINQ and lambdas - Get Control of your data)、p.497(Exercise)の解答を求めてみる。

コード

Critics.cs

using System;
namespace JimmyLinq
{
    public enum Critics
    {
        MuddyCritic,
        RottenTornadoes,
    }
}

コード

PriceRange.cs

using System;
namespace JimmyLinq
{
    public enum PriceRange
    {
        Cheap,
        Expensive,
    }
}

コード

Review.cs

using System;
namespace JimmyLinq
{
    public class Review
    {
        public int Issue { get; set; }
        public Critics Critic { get; set; }
        public double Score { get; set; }
        public Review()
        {
        }
    }
}

コード

ComicAnalyzer.cs

using System;
using System.Collections.Generic;
using System.Linq;

namespace JimmyLinq
{
    public static class ComicAnalyzer
    {
        private static PriceRange CalculatePriceRange(Comic comic)
        {
            if (Comic.Prices[comic.Issue] < 100)
            {
                return PriceRange.Cheap;
            }
            return PriceRange.Expensive;
        }

        internal static IEnumerable<IGrouping<PriceRange, Comic>>
            GroupComicsByPrice(IEnumerable<Comic> catalog,
            IReadOnlyDictionary<int, decimal> prices)
        {
            IEnumerable<IGrouping<PriceRange, Comic>> comics =
                from comic in catalog
                orderby prices[comic.Issue]
                group comic by CalculatePriceRange(comic) into comicGroup
                select comicGroup;
            return comics;
        }

        internal static IEnumerable<string>
            GetReviews(IEnumerable<Comic> catalog, IEnumerable<Review> reviews)
        {
            var rev =
                from comic in catalog
                orderby comic.Issue
                join review in reviews on comic.Issue equals review.Issue
                select $"{review.Critic} rated #{review.Issue} '{comic.Name}' {review.Score}";
            return rev; 
        }
    }
}

入出力結果(Terminal, Zsh)

Press G to group comics by price, R to get reviews, any other key to quit

Cheap comics:
#83 Tribal Tatto Madness: $25.75
#97 The Death of the Object: $35.25
#74 Black Monday: $75.00
Expensive comics:
#68 Revenge of the New Wave Freak (damaged): $250.00
#19 Rock and Roll (limited edition): $500.00
#36 Woman's Work: $650.00
#6 Johnny America vs. the Pinko: $3,600.00
#57 Hippie Madness (misprinted): $13,525.00

Press G to group comics by price, R to get reviews, any other key to quit

MuddyCritic rated #36 'Woman's Work' 37.6
RottenTornadoes rated #74 'Black Monday' 22.8
MuddyCritic rated #74 'Black Monday' 84.2
RottenTornadoes rated #83 'Tribal Tatto Madness' 89.4
MuddyCritic rated #97 'The Death of the Object' 98.1

Press G to group comics by price, R to get reviews, any other key to quit