2018年5月18日金曜日

開発環境

Head First C# ―頭とからだで覚えるC#の基本 (Andrew Stellman (著)、Jennifer Greene (著)、佐藤 嘉一 (監修, 監修)、木下 哲也 (翻訳)、オライリージャパン)の11章(LINQ データの管理)、プールパズル(p. 485)を取り組んでみる。

コード

using System;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        Line[] lines =
        {
            new Line(new string[]{"eating", "carrots,","but", "enjoy", "Horses" }, 1),
            new Line(new string[]{"zebras?", "hay","Cows", "bridge.", "bolted" }, 2),
            new Line(new string[]{"fork", "dogs!", "Engine", "and" }, 3),
            new Line(new string[]{"love", "they", "apples.", "eating" }, 2),
            new Line(new string[]{"whistled.", "Bump" }, 1)
        };

        var words =
            from line in lines
            group line by line.value
            into wordGroups
            orderby wordGroups.Key
            select wordGroups;

        var twoGroups = words.Take(2);

        foreach (var group in twoGroups)
        {
            int i = 0;
            foreach (Line inner in group)
            {
                i++;
                if (i == group.Key)
                {
                    var poem =
                       from word in inner.words
                       orderby word descending
                       select word + " ";
                    foreach (var word in poem)
                    {
                        Console.Write(word);
                    }
                }
            }
        }
    }
}
public class Line
{
    public string[] words;
    public int value;

    public Line(string[] words, int value)
    {
        this.words = words;
        this.value = value;
    }
}

入出力結果(コマンドプロンプト)

Horses enjoy eating carrots, but they love eating apples. 続行するには何かキーを押してください . . .

0 コメント:

コメントを投稿