LoginSignup
2
4

More than 5 years have passed since last update.

オブジェクトのpublicなプロパティの値をCSV文字列化する

Last updated at Posted at 2019-03-20

オブジェクトのpublicなプロパティの値をCSV文字列化するサンプルコード。
列はDataMemberのOrderで指定した順に出力する。
CSV文字列化したいクラスのTypeのGetPropertiesメソッドを呼び出すとpublicなプロパティのPropertyInfoを配列で取得できる。
GetPropertyメソッドはプロパティ個別にPropertyInfoを取得できる。

using System;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
namespace ConsoleApp1 {
    // CSV文字列化したいクラス
    class Student {
        [DataMember(Name = "id", Order = 1)]
        public int Id { set; get; }
        [DataMember(Name = "name", Order = 2)]
        public string Name { set; get; }
        [DataMember(Name = "v1")]
        public int V1 { set; get; }
        [DataMember(Name = "v2")]
        public int V2 { set; get; }
    }
    // CSV文字列化を拡張メソッドで実装してみた
    static class StudentExtension {
        public static string ToCsvString(this Student student) {
            var list = student.GetType().GetProperties()
                .OrderBy(_ => GetOrder(_))
                .ThenBy(_ => _.Name)
                .Select(_ => _.GetValue(student));
            return string.Join(", ", list);
        }
        private static int GetOrder(PropertyInfo info) {
            if (Attribute.GetCustomAttribute(info, typeof(DataMemberAttribute))
                is DataMemberAttribute attr)
            {
                return attr.Order;
            }
            return -1;
        }
    }
    // StudentクラスのCSV文字列化
    class Program {
        static void Main(string[] args) {
            var student = new Student() { Id = 1, Name = "山田", V1 = 1, V2 = 2 };
            Console.WriteLine(student.ToCsvString());
        }
    }
}
2
4
0

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
2
4