Comment detail

タブ区切りデータの処理 (Nested Flatten)
いまいちすっきりと書けません。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System;
using System.Collections.Generic;
using System.Text;
using VB_IO = Microsoft.VisualBasic.FileIO;

class Program {
    static void Main(string[] args) {
        //テーブルの準備
        List<string> headers = new List<string>();
        List<List<string>> table = new List<List<string>>();

        //TSVの読み込みにはMicrosoft.VisualBasic.FileIOTextFieldParserクラスが便利。CSVにも使えるよ。
        //Microsoft.VisualBasicを参照に加えてね。
        using(VB_IO.TextFieldParser tfp = new VB_IO.TextFieldParser(args[0], Encoding.GetEncoding("shift-jis"))) {
            tfp.SetDelimiters("\t");//区切り記号はタブ

            //通常のテキストファイルと同じ感覚で扱えます。
            headers.AddRange(tfp.ReadFields());
            while(!tfp.EndOfData) {
                table.Add(new List<string>(tfp.ReadFields()));
            }

            tfp.Close();
        }

        //第1カラムの値でデータを昇順にソートする。
        table.Sort((a, b) => (int.Parse(a[0]) - int.Parse(b[0])));//何回見ても書いてもラムダ式きもい。

        //第2カラムと第3カラムをヘッダを含めて入れ替える。
        headers.Reverse(1, 2);
        foreach(List<string> row in table){
            row.Reverse(1, 2);
            //第4カラムの値にそれぞれ1を加える。
            row[3] = (int.Parse(row[3]) + 1).ToString();
        }

        //出力
        foreach(string header in headers){
            Console.Write(header + "\t");
        }
        Console.WriteLine();
        foreach(List<string> row in table) {
            foreach(string cell in row) {
                Console.Write(cell + "\t");
            }
            Console.WriteLine();
        }
    }
}

Index

Feed

Other

Link

Pathtraq

loading...