189

I have a dataset objds. objds contains a table named Table1. Table1 contains column named ProcessName. This ProcessName contains repeated names.So i want to select only distinct names.Is this possible.

  intUniqId[i] = (objds.Tables[0].Rows[i]["ProcessName"].ToString());
adinas
  • 4,150
  • 3
  • 37
  • 47
Ahmed Atia
  • 17,848
  • 25
  • 91
  • 133
  • Post sample code, from a comment you made below, it seems the answer hinges on the specifics of the query you're working with. – MatthewMartin Jul 29 '09 at 12:23

18 Answers18

386
DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "Column1", "Column2" ...);
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • http://www.codeproject.com/Tips/153008/Select-DISTINCT-records-based-on-specified-fields – Charmie May 14 '13 at 08:20
  • if i have 2 columns "mo" and "name" i need to get the distinct "mo" but not the distinct "name" but i need to keep the column "name" in my datatable what shall i do? – User7291 Dec 05 '13 at 09:01
  • 1
    @JocelyneElKhoury, that doesn't really make sense... which value of "name" will you keep then? – Thomas Levesque Dec 05 '13 at 09:14
  • @ThomasLevesque it does not matter which one...let's say i need to keep the first value of the name – User7291 Dec 05 '13 at 09:16
  • 20
    OK, then you need grouping, not distinct. You could do it with Linq to DataSet: `table.AsEnumerable().GroupBy(row => row.Field("mo")).Select(group => group.First()).CopyToDataTable()` – Thomas Levesque Dec 05 '13 at 09:39
172

Following single line of code will avoid the duplicate rows of a DataTable:

dataTable.DefaultView.ToTable(true, "employeeid");

Where:

  • first parameter in ToTable() is a boolean which indicates whether you want distinct rows or not.

  • second parameter in the ToTable() is the column name based on which we have to select distinct rows. Only these columns will be in the returned datatable.

The same can be done from a DataSet, by accessing a specific DataTable:

dataSet.Tables["Employee"].DefaultView.ToTable(true, "employeeid");
mattumotu
  • 1,436
  • 2
  • 14
  • 35
Rahul
  • 1,721
  • 1
  • 10
  • 2
64
DataTable dt = new DataTable();
dt.Columns.Add("IntValue", typeof(int));
dt.Columns.Add("StringValue", typeof(string));
dt.Rows.Add(1, "1");
dt.Rows.Add(1, "1");
dt.Rows.Add(1, "1");
dt.Rows.Add(2, "2");
dt.Rows.Add(2, "2");

var x = (from r in dt.AsEnumerable()
        select r["IntValue"]).Distinct().ToList();
Martin Moser
  • 6,219
  • 1
  • 27
  • 41
36

With LINQ (.NET 3.5, C# 3)

var distinctNames = ( from row in DataTable.AsEnumerable()
 select row.Field<string>("Name")).Distinct();

 foreach (var name in distinctNames ) { Console.WriteLine(name); }
Zain Ali
  • 15,535
  • 14
  • 95
  • 108
19

You can use like that:

data is DataTable

data.DefaultView.ToTable(true, "Id", "Name", "Role", "DC1", "DC2", "DC3", "DC4", "DC5", "DC6", "DC7");  

but performance will be down. try to use below code:

data.AsEnumerable().Distinct(System.Data.DataRowComparer.Default).ToList();  

For Performance ; http://onerkaya.blogspot.com/2013/01/distinct-dataviewtotable-vs-linq.html

Gerhard Schlager
  • 3,155
  • 1
  • 31
  • 53
onerkaya
  • 221
  • 2
  • 2
15
var distinctRows = (from DataRow dRow in dtInventory.Rows
                                select dRow["column_name"] ).Distinct();

var distinctRows = (from DataRow dRow in dtInventory.Rows
                                select dRow["col1"], dRow["col2"].. ).Distinct();
Adi Lester
  • 24,731
  • 12
  • 95
  • 110
ces2601
  • 151
  • 1
  • 4
  • @Adi Lester: maybe select new { col1 = dRow["col1"], col2 = dRow["col2"], ...} ).Distinct(); is more correct? – Urik Mar 10 '13 at 14:29
  • When you just have a List you can do this: var test = (from DataRow dRow in vm.LiveAssets select dRow["manname"]).Distinct(); – pat capozzi Apr 12 '13 at 22:03
  • The first line works. The second, as Urik points out doesn't, but Urik's also does not work as Distinct() will not find equality when doing object-compare on anonymous types. – Alan Baljeu Oct 13 '18 at 17:34
10

To improve the above answer: The ToTable function on dataview has a "distinct" flag.

//This will filter all records to be distinct
dt = dt.DefaultView.ToTable(true);
Ravedave
  • 1,158
  • 2
  • 11
  • 24
  • 1
    This doesn't appear to work. There is only one overload with a distinct Boolean parameter in it and it requires the parameter array. I think this will just return a table called "True" without any DISTINCT applied. – proudgeekdad Oct 15 '10 at 17:17
  • 2
    +1 This actually does work (at least in .NET 4.5). If you specify the Boolean value "True" as the only parameter, it performs a DISTINCT on all columns in the DataView. – SetFreeByTruth Nov 22 '13 at 22:24
  • This works perfectly if you want distinct for all columns. – Merin Nakarmi Jun 22 '21 at 19:02
5

Following works. I have it working for me with .NET 3.5 SP1

// Create the list of columns
String[] szColumns = new String[data.Columns.Count];
for (int index = 0; index < data.Columns.Count; index++)
{
    szColumns[index] = data.Columns[index].ColumnName;
}

// Get the distinct records
data = data.DefaultView.ToTable(true, szColumns);
Noam M
  • 3,156
  • 5
  • 26
  • 41
Vijay Balani
  • 51
  • 1
  • 1
5

Syntax:-

DataTable dt = ds.Tables[0].DefaultView.ToTable(true, "ColumnName");

EX:-

DataTable uniqueCols = dsUDFlable.Tables[0].DefaultView.ToTable(true, "BorrowerLabelName");
JJS
  • 6,431
  • 1
  • 54
  • 70
user3639409
  • 51
  • 1
  • 1
3
string[] TobeDistinct = {"Name","City","State"};
DataTable dtDistinct = GetDistinctRecords(DTwithDuplicate, TobeDistinct);

//Following function will return Distinct records for Name, City and State column.
public static DataTable GetDistinctRecords(DataTable dt, string[] Columns)
{
    DataTable dtUniqRecords = new DataTable();
    dtUniqRecords = dt.DefaultView.ToTable(true, Columns);
    return dtUniqRecords;
}
JJS
  • 6,431
  • 1
  • 54
  • 70
Tanmay Nehete
  • 2,138
  • 4
  • 31
  • 42
3

I just happened to find this: http://support.microsoft.com/default.aspx?scid=kb;en-us;326176#1

While looking for something similar, only, specifically for .net 2.0

Im assuming the OP was looking for distinct while using DataTable.Select(). (Select() doesn't support distinct)

So here is the code from the above link:

class DataTableHelper 
{
    public DataTable SelectDistinct(string TableName, DataTable SourceTable, string FieldName)
    {   
        DataTable dt = new DataTable(TableName);
        dt.Columns.Add(FieldName, SourceTable.Columns[FieldName].DataType);

        object LastValue = null; 
        foreach (DataRow dr in SourceTable.Select("", FieldName))
        {
            if (  LastValue == null || !(ColumnEqual(LastValue, dr[FieldName])) ) 
            {
                LastValue = dr[FieldName]; 
                dt.Rows.Add(new object[]{LastValue});
            }
        }

        return dt;
    }

    private bool ColumnEqual(object A, object B)
    {

        // Compares two values to see if they are equal. Also compares DBNULL.Value.
        // Note: If your DataTable contains object fields, then you must extend this
        // function to handle them in a meaningful way if you intend to group on them.

        if ( A == DBNull.Value && B == DBNull.Value ) //  both are DBNull.Value
            return true; 
        if ( A == DBNull.Value || B == DBNull.Value ) //  only one is DBNull.Value
            return false; 
        return ( A.Equals(B) );  // value type standard comparison
    }
}
Noam M
  • 3,156
  • 5
  • 26
  • 41
gideon
  • 19,329
  • 11
  • 72
  • 113
3

it is easy

    DataView view = new DataView(dt);
DataTable dt2 = view.ToTable(true, "Column1", "Column2","Column3", ...,"ColumnNth");

and dt2 datatable contain column1,Column2..ColumnNth unique data.

Manish Singh
  • 934
  • 1
  • 12
  • 27
2
var ValuetoReturn = (from Rows in YourDataTable.AsEnumerable()
select Rows["ColumnName"]).Distinct().ToList();
Siyavash
  • 452
  • 1
  • 5
  • 13
2

The most simple solution is to use LINQ and then transform the result to a DataTable

    //data is a DataTable that you want to change
    DataTable result = data.AsEnumerable().Distinct().CopyToDataTable < DataRow > ();

This is valid only for asp.net 4.0 ^ Framework and it needs the reference to System.Data.DataSetExtensions as Ivan Ferrer Villa pointed out

Davide Castronovo
  • 1,366
  • 8
  • 21
1
DataTable dt = new DataTable("EMPLOYEE_LIST");

DataColumn eeCode = dt.Columns.Add("EMPLOYEE_CODE", typeof(String));
DataColumn taxYear = dt.Columns.Add("TAX_YEAR", typeof(String));
DataColumn intData = dt.Columns.Add("INT_DATA", typeof(int));
DataColumn textData = dt.Columns.Add("TEXT_DATA", typeof(String));

dt.PrimaryKey = new DataColumn[] { eeCode, taxYear };

It filters data table with eecode and taxyear combinedly considered as unique

JJS
  • 6,431
  • 1
  • 54
  • 70
0
objds.Table1.Select(r => r.ProcessName).AsEnumerable().Distinct();
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
  • Hi @GálGyula, welcome to Stack Overflow! Here we care about answers with good explanations, not just code. Only post an answer if it really solves the question and you can explain how. To improve your future answers, take a look the the guide [how do I write a good answer](https://stackoverflow.com/help/how-to-answer). – Erick Petrucelli Dec 14 '18 at 13:25
-1
DataTable dtbs = new DataTable(); 
DataView dvbs = new DataView(dt); 
dvbs.RowFilter = "ColumnName='Filtervalue'"; 
dtbs = dvbs.ToTable();
-2

sthing like ?

SELECT DISTINCT .... FROM table WHERE condition

http://www.felixgers.de/teaching/sql/sql_distinct.html

note: Homework question ? and god bless google..

http://www.google.com/search?hl=en&rlz=1C1GGLS_enJO330JO333&q=c%23+selecting+distinct+values+from+table&aq=f&oq=&aqi=

Madi D.
  • 1,980
  • 5
  • 23
  • 44
  • 3
    to whomever downvoted me :S,, obviously the question was modified after my answer ?? (answer 10:15, question edited on 12:15 ) oh well.. thx for ur ignorance :) – Madi D. Oct 22 '09 at 08:16
  • 4
    OP asks for how to select distinct rows in a C# ado.net environment, not in an actual database. – aggaton Mar 02 '16 at 21:49