1public class Student{2 public string Name { get; set;}3 public string Age { get; set;}4:5:6//stringのプロパティが大量にあるとします。7}89public staticvoidmain(string[] args){1011//データ12 List<string> list = new List<string>(){"TARO","17",....};1314//案1:コンストラクタ、もしくはプロパティを逐一更新。(これは避けたいです。)15 Student taro = new Student(list[0],list[1],....);16 Student taro = new Student(){Name=list[0], Age=list[0],...};1718//案2:インデックスとプロパティの順番の整合性が取れない場合がある?19 Student obj = new Student();20foreach(var prop in typeof(Student).GetProperties().Select((item,idx)=>(item, idx))){21 prop.SetValue(obj, list[idx]);22}2324}
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Reflection;56namespace ConsoleApp1
7{8 public class Student
9{10 public string Name { get; set;}11 public string Age { get; set;}1213 public static Student ParseList(IReadOnlyList<string> list)14{15 var result = new Student();16 result.Apply(list);17return result;18}1920 public voidApply(IReadOnlyList<string> list)21{22if(list.Count != applyList.Count)23{24 throw new ArgumentException(nameof(list));25}26for(int i =0; i < list.Count; i++)27{28 properties[applyList[i]].SetValue(this, list[i]);29}30}3132 private static readonly Dictionary<string, PropertyInfo> properties =typeof(Student)33.GetProperties()34.ToDictionary(a => a.Name);35 private static readonly List<string> applyList = new List<string>()36{37nameof(Name),nameof(Age)38};39}4041 class Program
42{43staticvoidMain(string[] args)44{45 var students = new[]46{47 new[]{"山田太郎","17"},48 new[]{"山田二郎","17"},49 new[]{"佐藤花子","16"},50};51foreach(var list in students)52{53 var student = Student.ParseList(list);54 Console.WriteLine($"{student.Name}: {student.Age}");55}56 Console.ReadKey();57}58}59}
1public class Student {2 public List<string> Values { get;}= new List<string>();3 public string Name { get => Values[0], set => Values[0]= value }4 public string Age { get => Values[1], set => Values[1]= value }5}