5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

List<T>をArrayListに変換する拡張メソッド

Posted at

はじめに

自作クラスのListの内容をCSVにはきだしたいという事案が発生した。
いちいちメンバを1つ1つ書いていくのは面倒ですよね。
てことでListをArrayListに変換する拡張メソッドを作成した。
正確にはLINQ to Objectも受け入れたかったのでIEnumerableの拡張にしました。
これでいちいちClassの内容を取り出さなくても大丈夫。。。かも。

拡張メソッド本体

/// <summary>
/// List<T>拡張メソッド
/// </summary>
static class ListExtensions
{
	/// <summary>
	/// Listに格納されたClassデータをArrayListに変換
	/// </summary>
	/// <typeparam name="T">型</typeparam>
	/// <param name="list">コレクションデータ</param>
	/// <returns>
	/// ArrayListデータ
	/// </returns>
	public static ArrayList ToArrayList<T>(this IEnumerable<T> list)
	{
		// null または データがない場合
		if (list == null || list.Count() == 0) return new ArrayList();

		ArrayList result = new ArrayList();

		foreach (T data in list)
		{
			// PropertyInfoを取得
			PropertyInfo[] props = data.GetType().GetProperties();
			// MemberTypeで絞らない場合SelectだけでOK
			var q = props.Where(x => x.MemberType == MemberTypes.Property).Select(x => x.GetValue(data)).ToArray();
			// 配列に追加
			result.Add(q);
		}

		return result;
	}
}

使い方

List<Employee> empList = new Employee();
ArrayList array = empList.ToArrayList<Employee>();
5
6
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
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?