この汎用ヘルパー関数は、オブジェクトのリストを反復処理し、それらのパブリック プロパティにアクセスして、オブジェクトごとに 1 つのカンマ区切りの文字列を吐き出します。
/// <summary>
/// Format the properties as a list of comma delimited values, one object row per.
/// </summary>
/// <typeparam name="T">Type of class contained in the List</typeparam>
/// <param name="list">A list of objects</param>
/// <returns>a list of strings in csv format</returns>
public static List<string> ToCSV<T>(this IEnumerable<T> list)
where T : class
{
var results = new List<string>();
bool firstTime = true;
foreach (var obj in list)
{
// header data
if (firstTime)
{
firstTime = false;
string line = String.Empty;
foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
{
if (propertyInfo.CanRead)
{
line += propertyInfo.Name + ',';
}
}
results.Add(line);
}
else
{
string line = String.Empty;
foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
{
if (propertyInfo.CanRead)
{
object value = propertyInfo.GetValue(obj, null);
if (value.GetType() == typeof(string))
{
line += "\"" + value.ToString() + "\"" + ",";
}
else
{
line += value.ToString() + ",";
}
}
}
results.Add(line);
}
}
return results;
}
このメソッドによって反復されるクラスの 1 つに、切り捨てられる文字列プロパティがあります。
string BusinessItem { get; set; } // "0000", a legitimate business value
問題のビットはここにあります:
object value = propertyInfo.GetValue(obj, null); // value == 0
プロパティの値を int ではなく文字列として取得するにはどうすればよいですか?