情報応用演習Ⅰ(2024)

【T2c】LINQ(2/4)

プロジェクトタイプC#コンソールアプリ※
プロジェクト名T2c
ソリューション名PIT2
ターゲットフレームワーク.NET 8.0(長期的なサポート)
最上位レベルのステートメントを使用しない使用する(チェックオフ)

※ 「コンソールアプリ(.NET Framework)」ではないので注意せよ!

2c-2. 従来の絞り込み処理

まずはC#の「コンソールアプリ」タイプのプロジェクトを作成しよう( 「コンソールアプリ(.NET Framework)」ではないので注意せよ ). 上表に示すように,プロジェクト名はT2cとする. ターゲットフレームワークとして「.NET 8.0(長期的なサポート)」を選択し,「最上位レベルのステートメントを使用しない」には チェックが入っていない ことを確認しよう. プロジェクトを作成したら,T2aと同様にプロジェクトにStudentクラスを追加しよう.

Program.csは_のように書こう(手打ちするには量が多いのでここはコピペ推奨). ここではStudentクラスの配列(要素数16)を作成している.

Program.csの内容 - Studentクラスの配列
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
using T2c;

var students = new[]
{
        new Student(){ ID =13, Name = "鈴無 音々",   Birthday = new DateTime(1998, 9,30) },
        new Student(){ ID = 3, Name = "浅野 みいこ", Birthday = new DateTime(2003, 1,10) },
        new Student(){ ID = 1, Name = "想影 真心",   Birthday = new DateTime(2000, 3, 8) },
        new Student(){ ID =11, Name = "宇佐美 秋春", Birthday = new DateTime(2001,11,21) },
        new Student(){ ID = 5, Name = "石凪 萌太",   Birthday = new DateTime(2000, 3, 8) },
        new Student(){ ID = 2, Name = "井伊 遥奈",   Birthday = new DateTime(2000, 4,10) },
        new Student(){ ID = 8, Name = "葵井 巫女子", Birthday = new DateTime(2002, 6, 1) },
        new Student(){ ID =15, Name = "嵯峨埜 鵜鷺", Birthday = new DateTime(2000, 3,25) },
        new Student(){ ID = 4, Name = "闇口 崩子",   Birthday = new DateTime(2000, 3,22) },
        new Student(){ ID =14, Name = "形梨 らぶみ", Birthday = new DateTime(2003, 6,12) },
        new Student(){ ID =12, Name = "石丸 小唄",   Birthday = new DateTime(2001,10, 3) },
        new Student(){ ID = 9, Name = "江本 智恵",   Birthday = new DateTime(2000, 3,28) },
        new Student(){ ID =10, Name = "貴宮 むいみ", Birthday = new DateTime(1999, 7,13) },
        new Student(){ ID = 7, Name = "隼 荒唐丸",   Birthday = new DateTime(2002, 5,15) },
        new Student(){ ID = 6, Name = "七々見 奈波", Birthday = new DateTime(1980, 3,11) },
        new Student(){ ID =16, Name = "木賀峰 約",   Birthday = new DateTime(2003, 2,11) },
};// end of array

さて,この配列studentsから何らかの条件に合致するデータだけを表示するにはどうしたらよいだろうか. たとえば,この配列から「誕生日(Birthdayプロパティ)が2000年以前である」学生の情報だけを表示するにはどうしたらよいだろうか.

もっとも単純な方法は for 文や foreach 文を用いて,要素を一つずつチェックする方法である. Program.cs に_のように追記してみよう.

Program.csの内容 - 従来の方法での絞り込み処理
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
using T2c;

var students = new[]
{
    // ... (長いので省略) ...
};// end of array

foreach (var s in students)
{
    if (s.Birthday.Year <= 2000) // 誕生日が2000年以前
    {
        Console.WriteLine($"{s.ID,2}: {s.Name} ({s.Birthday:yyyy-MM-dd})");
    }// if
}//foreach

追記したら実行してみよう(スタートアッププロジェクトをこのプロジェクトに変更するのを忘れずに). _の実行結果は_のようになる.

13: 鈴無 音々 (1998-09-30)
 1: 想影 真心 (2000-03-08)
 5: 石凪 萌太 (2000-03-08)
 2: 井伊 遥奈 (2000-04-10)
15: 嵯峨埜 鵜鷺 (2000-03-25)
 4: 闇口 崩子 (2000-03-22)
 9: 江本 智恵 (2000-03-28)
10: 貴宮 むいみ (1999-07-13)
 6: 七々見 奈波 (1980-03-11)
実行結果
Last updated on 2024-04-26
Published on 2024-04-26

Powered by Hugo. Theme by TechDoc. Designed by Thingsym.