Select Distinct en un DataTable o DataSet

22 09 2008

(Este post es solo para programadores)

Buenas, el otro día andaba buscando como hacer un select distinct sobre un data table de .NET y resulta que con la función select del DataTable no se puede hacer un distinct para obtener las filas que son distintas dada una columna.

Estuve buscando en internet y encontré un par de soluciones pero no me servían porque devolvían los resultados en una sola columna con las filas distintas(en concreto esta de Microsoft y esta).

Así que como necesitaba algo que se pareciese más a un select distinct de SQL me hice mi propia función que es la siguiente:

C#:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class DataSetHelper
    {
        public static DataTable selectDisctinct(DataTable dt, string columnName)
        {
            try
            {
                if (columnName == null || columnName.Length == 0)
                       throw new ArgumentNullException(columnName, "El parámetro no puede ser nulo");
                DataTable distintos = dt.DefaultView.ToTable(true, columnName);
                DataTable aux = new DataTable();
                foreach (DataColumn dc in dt.Columns)
                    aux.Columns.Add(new DataColumn(dc.Caption,dc.DataType));
                foreach (DataRow dr in distintos.Rows)
                {
                    aux.ImportRow(dt.Select(columnName + " = '" + dr[0] + "'")[0]);
                }
                return aux;
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
    }

es necesario incluir el namespace System.Data:
using System.Data;

Espero que sea útil.
Referencias:
http://weblogs.asp.net/eporter/archive/2005/02/10/370548.aspx
http://support.microsoft.com/default.aspx?scid=kb;en-us;326176#1

Entradas relacionadas

    Insertar en Excel desde C# con OleDb
    SDL joystick + Playstation DualShock

Actions

Informations

One response to “Select Distinct en un DataTable o DataSet”

3 10 2008
Jorge (19:30:42) :

Muy bueno, justo lo que estaba buscando para no realizar un doble Query.
Saludos!!

Se aprecian los comentarios

You can use these tags : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">