Trigger4Win/Trigger/Extensions/DataTable.cs
2015-04-10 00:09:58 +00:00

49 lines
No EOL
1.8 KiB
C#

using System;
using System.Text;
using System.Data;
using System.Collections.Generic;
namespace ExtensionMethods
{
/// <summary>
/// <para>Add extensions to <c><see cref="DataTable"/></c></para>
/// </summary>
public static class DataTableExtensions
{
/// <summary>
/// <para>Converts the first column of the specified <paramref name="dataTable"/> to a <see cref="List&lt;T&gt;"/></para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dataTable"></param>
/// <returns></returns>
public static List<T> ToList<T>(this DataTable dataTable)
{
return ToList<T>(dataTable, 0);
}
/// <summary>
/// <para>Converts the column with the specified <paramref name="columnName"/> of the specified <paramref name="dataTable"/> to a <see cref="List&lt;T&gt;"/></para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dataTable"></param>
/// <param name="columnName">Name of the column that shall be converted</param>
/// <returns></returns>
public static List<T> ToList<T>(this DataTable dataTable, string columnName)
{
return ToList<T>(dataTable, dataTable.Columns.IndexOf(columnName));
}
/// <summary>
/// <para>Converts the column with the specified <paramref name="columnIndex"/> of the specified <paramref name="dataTable"/> to a <see cref="List&lt;T&gt;"/></para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dataTable"></param>
/// <param name="columnIndex">Index of the column that shall be converted</param>
/// <returns></returns>
public static List<T> ToList<T>(this DataTable dataTable, int columnIndex)
{
List<T> list = new List<T>(dataTable.Rows.Count);
foreach (DataRow row in dataTable.Rows)
list.Add((T)Convert.ChangeType(row[columnIndex], typeof(T)));
return list;
}
}
}