0
1

[C#]Splitメソッドの戻り値(配列型)をリストに変換する

Last updated at Posted at 2024-09-25

C#で、Splitメソッドを使うと、戻り値は配列(string[])として返されますが、それをリスト(List)に変換する方法はいくつかあります。

1. ToList メソッドを使う方法

最もシンプルな方法は、配列をリストに変換するために ToList メソッドを使うことです。

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

class Program
{
    static void Main()
    {
        string text = "apple,banana,cherry";
        string[] words = text.Split(',');
        
        // 配列をリストに変換
        List<string> wordList = words.ToList();
        // using System.Linq;を記載しない場合、以下のようにコーディングする必要あり
        //List<string> wordList = System.Linq.Enumerable.ToList(words);
        
        // 結果を表示
        foreach (var word in wordList)
        {
            Console.WriteLine(word);
        }
    }
}

特徴:
ToListメソッドは、配列を簡単にリストに変換できます。
メリット:
簡単: 1行でリストに変換できるのでコードがすっきりします。
デメリット:
ライブラリの追加: ToListメソッドを使うためには、System.Linqというライブラリをインポート(using System.Linq;)する必要があります。

2. コンストラクタを使う方法

リストには、配列をそのまま受け取ってリストを作るコンストラクタがあります。

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        string text = "apple,banana,cherry";
        string[] words = text.Split(',');
        
        // コンストラクタを使って配列からリストを作成
        List<string> wordList = new List<string>(words);
        
        // 結果を表示
        foreach (var word in wordList)
        {
            Console.WriteLine(word);
        }
    }
}

特徴:
リストのコンストラクタに配列を渡すことでリストを作成します。
メリット:
追加のライブラリ不要: ToListメソッドを使わずに済むため、System.Linqをインポートする必要がありません。
デメリット:
少し長い: コンストラクタの使い方を理解するために少しコードが増える場合があります。

3. ループで手動でリストに追加する方法

配列の要素を1つずつループでリストに追加する方法です。

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        string text = "apple,banana,cherry";
        string[] words = text.Split(',');
        
        // 空のリストを作成
        List<string> wordList = new List<string>();
        
        // 配列の各要素をリストに追加
        foreach (var word in words)
        {
            wordList.Add(word);
        }
        
        // 結果を表示
        foreach (var word in wordList)
        {
            Console.WriteLine(word);
        }
    }
}

特徴:
自分でリストを作り、配列の要素を1つずつリストに追加します。
メリット:
カスタマイズ性が高い: 追加する際に何か処理をしたい場合など、柔軟にコードを変更できます。
デメリット:
手間がかかる: 他の方法に比べて、少し長いコードが必要です。

まとめ

ToList メソッド: 最も簡単でおすすめ。ただし、System.Linqを使う必要がある。
コンストラクタ: ライブラリ不要でスッキリしています。
ループで手動変換: 柔軟だが、他の方法に比べて手間がかかる。
初学者の場合は、ToListメソッドを使うのが一番簡単で扱いやすいのでおすすめです!

練習問題

paizaレベルアップ問題集 【N 行 M 列のデータの入力】行ごとに要素数の異なる整数列の入力 (paizaランク D 相当)

0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1