PR

【C#】List 操作の基本を学ぼう!

【C#】
広告

はじめに

C#のList<T>クラスは、ジェネリックコレクションの一つで、データのリストを効率的に管理するために使用されます。List<T>は配列に似ていますが、動的にサイズを変更できるため、要素の追加や削除が簡単に行えます。本記事では、C#のList<T>クラスの基本的な操作について、具体的なコード例を交えながら解説します。これにより、List<T>の使用方法を理解し、日常のプログラミングに役立てることができるでしょう。

Listの基本操作

Listの作成と初期化

List<T>を使用するには、まずリストを作成し、必要に応じて初期化します。以下の例では、整数のリストを作成し、初期値を設定しています。

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        // 空のリストを作成
        List<int> numbers = new List<int>();

        // 初期値を設定してリストを作成
        List<int> initializedNumbers = new List<int> { 1, 2, 3, 4, 5 };

        // リストの内容を表示
        foreach (int number in initializedNumbers)
        {
            Console.WriteLine(number);
        }
    }
}

要素の追加

List<T>に要素を追加するには、Addメソッドを使用します。以下の例では、リストに整数を追加しています。

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<int> numbers = new List<int>();
        numbers.Add(1);
        numbers.Add(2);
        numbers.Add(3);

        // リストの内容を表示
        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}

要素の挿入

特定の位置に要素を挿入するには、Insertメソッドを使用します。以下の例では、リストの2番目の位置に数値4を挿入しています。

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3 };
        numbers.Insert(1, 4); // インデックス1の位置に4を挿入

        // リストの内容を表示
        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}

要素の削除

リストから要素を削除するには、RemoveメソッドまたはRemoveAtメソッドを使用します。

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
        numbers.Remove(3); // 値3を持つ要素を削除
        numbers.RemoveAt(1); // インデックス1の要素を削除

        // リストの内容を表示
        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}

要素の検索

リスト内の要素を検索するには、ContainsメソッドやFindメソッドを使用します。

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

        // 要素の存在を確認
        bool containsThree = numbers.Contains(3);
        Console.WriteLine("Contains 3: " + containsThree);

        // 条件に一致する最初の要素を検索
        int firstEvenNumber = numbers.Find(x => x % 2 == 0);
        Console.WriteLine("First even number: " + firstEvenNumber);
    }
}

Listの応用操作

リストのソート

リストをソートするには、Sortメソッドを使用します。

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<int> numbers = new List<int> { 5, 3, 1, 4, 2 };
        numbers.Sort();

        // リストの内容を表示
        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}

リストのフィルタリング

特定の条件に基づいてリストをフィルタリングするには、FindAllメソッドを使用します。

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
        List<int> evenNumbers = numbers.FindAll(x => x % 2 == 0);

        // フィルタリングされたリストの内容を表示
        foreach (int number in evenNumbers)
        {
            Console.WriteLine(number);
        }
    }
}

リストの変換

リストの各要素を変換するには、ConvertAllメソッドを使用します。

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
        List<string> stringNumbers = numbers.ConvertAll(x => "Number: " + x);

        // 変換されたリストの内容を表示
        foreach (string str in stringNumbers)
        {
            Console.WriteLine(str);
        }
    }
}

リストの結合

複数のリストを結合するには、AddRangeメソッドを使用します。

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<int> firstList = new List<int> { 1, 2, 3 };
        List<int> secondList = new List<int> { 4, 5, 6 };

        firstList.AddRange(secondList);

        // 結合されたリストの内容を表示
        foreach (int number in firstList)
        {
            Console.WriteLine(number);
        }
    }
}

Listの使い所

データの管理

List<T>は、データのコレクションを管理するための強力なツールです。例えば、学生の成績や商品の在庫管理など、複数のデータを効率的に管理できます。

using System;
using System.Collections.Generic;

public class Student
{
    public string Name { get; set; }
    public int Score { get; set; }
}

public class Program
{
    public static void Main()
    {
        List<Student> students = new List<Student>
        {
            new Student { Name = "Alice", Score = 85 },
            new Student { Name = "Bob", Score = 92 },
            new Student { Name = "Charlie", Score = 78 }
        };

        // 学生の情報を表示
        foreach (Student student in students)
        {
            Console.WriteLine($"Name: {student.Name}, Score: {student.Score}");
        }
    }
}

動的なデータの追加と削除

List<T>は、動的なデータの追加と削除に適しています。例えば、ユーザーの入力に応じてリストにデータを追加したり削除したりする場合に便利です。

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<string> tasks = new List<string>();

        // タスクの追加
        tasks.Add("Task 1");
        tasks.Add("Task 2");

        // タスクの削除
        tasks.Remove("Task 1");

        // タスクの内容を表示
        foreach (string task in tasks)
        {
            Console.WriteLine(task);
        }
    }
}

リストのコピー

リストをコピーする必要がある場合、List<T>のコンストラクタを使用して簡単にコピーを作成できます。

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<int> originalList = new List<int> { 1, 2, 3, 4, 5 };
        List<int> copyList = new List<int>(originalList);

        // コピーされたリストの内容を表示
        foreach (int number in copyList)
        {
            Console.WriteLine(number);
        }
    }
}

まとめ

本記事では、C#のList<T>クラスの基本的な操作について解説しました。List<T>の作成と初期化、要素の追加、挿入、削除、検索、ソート、フィルタリング、変換、結合など、様々な操作方法を具体的なコード例とともに紹介しました。List<T>は、動的なデータの管理に非常に便利なクラスであり、日常のプログラミングにおいて頻繁に使用されます。この記事を参考に、List<T>の基本を理解し、効率的なデータ管理を実現してください。

広告
【C#】
広告
タイトルとURLをコピーしました