LoginSignup
26
21

More than 5 years have passed since last update.

二次元Listジェネリックにファイル読み込み

Posted at

概要

 タブ区切りのtxtファイルを読み込み、その内容を2次元ListのジェネリックList<List<string>>
へと格納して呼び出し側に返すメソッドを作る。
 仕事で取り組んだ時に、2次元ジェネリックの格納に不慣れで手間取ったのと、情報が少なかったため投稿

内容

LoadFileData.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace test
{
    static class FileLoad
    {
        public static List<List<string>> load(string filename)
        {
            List<List<string>> LoadFileData = new List<List<string>>();
            string filepath = "テキストファイルがあるパス";
            filepath += filename;
            try
            {
                using (StreamReader sr = new StreamReader(filepath, Encoding.GetEncoding("utf-8")))
                {
                    //sr.ReadLine(); 最初の一行分(表のヘッダ部分)を飛ばしたい場合
                    while (!sr.EndOfStream)
                    {
                        List<string> addData = new List<string>();
                        string line = sr.ReadLine();//一行ずつ読み込む
                        string[] splitData = line.Split('\t');//タブ区切りで分割したものを配列に追加
                        for (int i = 0; i < splitData.Length; i++)
                        {
                            addData.Add(splitData[i]);//追加用のList<string>の作成
                        }
                        addData.Add("\n");
                        LoadFileData.Add(addData);//List<List<string>>のList<string>部分の追加
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return LoadFileData;
        }
    }
}

出力用

main.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace test
{
  class Program
  {
     static void Main(string[] args)
     {
            List<List<string>> loadData = (FileLoad.load("sample.txt"));
            for (int i = 0; i < loadData.Count; i++)//ジェネリックの出力
            {
                foreach (string data in loadData[i])
                {
                    Console.Write(data);
                }
            }
            Console.ReadKey();            
        }
    }
}

ファイルの中身

sample.txt
名前  アドレス    コメント
hamutaro    koushi@example.com  ハムタロサァンwww
hoge太郎  hogehoge@example.com    hogehoge
null彦 nullnull@example.com    ヌルポ

実行結果
実行結果.png

このように行単位で読み込んだ内容を出力できることを確認した。

まとめ

2次元ジェネリックに要素を追加する際に、始めは直接2次元配列風に
LoadFileData[0][0].add(xxx)のようにしてみたがエラー
となり、2次元の添字指定をしたaddはできなかった。

だが、難しく考えずにジェネリックの表記通りにListに対して、別で作成したListをaddすればよいというだけだった。

26
21
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
26
21