17
avril
2007
DataTable.Select typé
avril
2007
A mon avis le Select sur un DataTable a deux défauts :
- Comme nous l’avons vu dans un post précédent, il vaut mieux préférer les IEnumerable aux tableaux (surtout en C# 3.0)
- la méthode Select nous retourne un tableau de DataRow. Quand on travaille avec une table typée (héritant de
TypedTableBase<T>
en C#3.0), il est souvent pénible de devoir caster chaque élément.
Pour résoudre cela, je suis passé par les extension methods
namespace System.Data
{
public static class DataTableExtension
{
public static IEnumerable<DataRowType> SelectTyped<DataRowType>(this TypedTableBase<DataRowType> table)
where DataRowType : DataRow
{
return table.Select().Cast<DataRowType>();
}
public static IEnumerable<DataRowType> SelectTyped<DataRowType>(this TypedTableBase<DataRowType> table, string filter)
where DataRowType : DataRow
{
return table.Select(filter).Cast<DataRowType>();
}
public static IEnumerable<DataRowType> SelectTyped<DataRowType>(this TypedTableBase<DataRowType> table, string filter, string sort)
where DataRowType : DataRow
{
return table.Select(filter, sort).Cast<DataRowType>();
}
public static IEnumerable<DataRowType> SelectTyped<DataRowType>(this TypedTableBase<DataRowType> table, string filter, string sort, DataViewRowState rowState)
where DataRowType : DataRow
{
return table.Select(filter, sort, rowState).Cast<DataRowType>();
}
}
}
{
public static class DataTableExtension
{
public static IEnumerable<DataRowType> SelectTyped<DataRowType>(this TypedTableBase<DataRowType> table)
where DataRowType : DataRow
{
return table.Select().Cast<DataRowType>();
}
public static IEnumerable<DataRowType> SelectTyped<DataRowType>(this TypedTableBase<DataRowType> table, string filter)
where DataRowType : DataRow
{
return table.Select(filter).Cast<DataRowType>();
}
public static IEnumerable<DataRowType> SelectTyped<DataRowType>(this TypedTableBase<DataRowType> table, string filter, string sort)
where DataRowType : DataRow
{
return table.Select(filter, sort).Cast<DataRowType>();
}
public static IEnumerable<DataRowType> SelectTyped<DataRowType>(this TypedTableBase<DataRowType> table, string filter, string sort, DataViewRowState rowState)
where DataRowType : DataRow
{
return table.Select(filter, sort, rowState).Cast<DataRowType>();
}
}
}
Et pour l’utiliser :
static void Main(string[] args)
{
var ds = new DataSet1();
ds.DataTable1.AddDataTable1Row("test");
ds.DataTable1.AddDataTable1Row("test2");
foreach (var dataRow in ds.DataTable1.SelectTyped("DataColumn1 = 'test'"))
Console.WriteLine(dataRow.DataColumn1);
Console.ReadLine();
}
{
var ds = new DataSet1();
ds.DataTable1.AddDataTable1Row("test");
ds.DataTable1.AddDataTable1Row("test2");
foreach (var dataRow in ds.DataTable1.SelectTyped("DataColumn1 = 'test'"))
Console.WriteLine(dataRow.DataColumn1);
Console.ReadLine();
}
C’est vraiment bien sympa la déduction par le compilateur du type generic.